Home > Enterprise >  Why do I keep getting Syntax Error: JSON parse even though my code works with another API?
Why do I keep getting Syntax Error: JSON parse even though my code works with another API?

Time:10-31

Working with React and I continually get a SyntaxError:JSON.parse when I try to fetch from the API. I'm able to fetch the data just fine when working with a different API.

What am I doing wrong here? I'm a complete newb when it comes to API's so please don't eviscerate me if this is a stupid question :D

   const API_URL = 'www.themealdb.com/api/json/v1/1/search.php?s=Arrabiata';

    const getMealRequest = async()=>{
        const response = await fetch(API_URL)
        const data = await response.json()
        console.log(data)
    }
    
    useEffect(()=>{
        getMealRequest()
    },[])

CodePudding user response:

const API_URL = 'https://www.themealdb.com/api/json/v1/1/search.php?s=Arrabiata';

const getMealRequest = async() => {
  const response = await fetch(API_URL)
  const data = await response.json()
  console.log(data)
}

getMealRequest()
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

You forgot to include protocol: incude https:// before the address and it will work:

CodePudding user response:

There is an error on your API call which is not related to this question. You didn't implement try/cath block with the getMealRequest so in the failure case, the response is not a valid object to parse and you get the mentioned error.

To solve it:


const getMealRequest = async () => {
  try {
    const response = await fetch('https://www.themealdb.com/api/json/v1/1/search.php?s=Arrabiata'
)
    const data = await response.json()
    console.log(data)
  } catch (error) {
    console.log(error)
  }
}

Now inspect your console and see what is wrong with your API call. also, you can check the network tab for further detail about the request and response on calling API_URL.

  • Related