Reputation: 105
I'm new to React and I get an error in my console (see below) when I try to convert data to JSON. This is probably not the correct way of doing it. Anyone knows how to fix this? I want to display the fetched data in my console.
App.js:27 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
App.js
const API_ID = "xxxxx";
const API_KEY = "xxxxxxxxxx";
class App extends Component{
//function to get recipe
getRecipe = async (e) => {
const recipeName = e.target.elements.recipeName.value;
e.preventDefault();
const api_call = await fetch(`curl "https://api.edamam.com/search?q=chicken&app_id=${API_ID}&app_key=${API_KEY}&from=0&to=3&calories=591-722&health=alcohol-free"
`);
const data = await api_call.json();
console.log(data);
}
Upvotes: 0
Views: 3559
Reputation: 225
Fetch needs only the URL you're making the http request to as first param.
const response = await fetch('https://api.edamam.com/search?q=chicken&app_id=${API_ID}&app_key=${API_KEY}&from=0&to=3&calories=591-722&health=alcohol-free');
const jsonResponse = await response.json();
You are correct to parse the response to json afterwards, but when the url is incorrect, fetch will return empty response. Trying to parse the empty response will result in the error you've described.
Just to make things clear, curl is a cli tool (not js browser api, like fetch) that performs http requests. It does the same job as fetch, but in different contexts. So you do not need to call it, or specify it as part of the url you provide to fetch.
Upvotes: 1
Reputation: 9105
As mentioned in the question in the code snippet there was a adding of curl as shown below
Instead of this
const api_call = await fetch(`curl "https://api.edamam.com/search?q=chicken&app_id=${API_ID}&app_key=${API_KEY}&from=0&to=3&calories=591-722&health=alcohol-free"`);
Use
const api_call = await fetch(`https://api.edamam.com/search?q=chicken&app_id=${API_ID}&app_key=${API_KEY}&from=0&to=3&calories=591-722&health=alcohol-free"`);
Kindly remove it and i hope it should work.
Upvotes: 2