Home > other >  react-jsonp giving a CORB error in a React App
react-jsonp giving a CORB error in a React App

Time:01-16

Edit based on suggestions tried doing it with fetch, now I am getting this

enter image description here

enter image description here

I am trying to get data from gnews.io/api in a simple react app.I am learning React and the solution might have been to easy but I am stuck here and cant figure out what is wrong and I keep getting this error

fetch-jsonp.js:88 Cross-Origin Read Blocking (CORB) blocked cross-origin response https://gnews.io/api/v4/top-headlines?country=us&token=myapi with MIME type application/json.

funny thing is that if I copy this url https://gnews.io/api/v4/top-headlines?country=us&token=MYAPI&callback=jsonp_1642257010280_37644 and paste it in the browser I am getting the desired response.

Would really appreciate any sort of help

this is the useEffect function that is making this api call

React.useEffect(()=> {
    async function getNewsdata(country){
        try {
            
            let url = `https://www.gnews.io/api/v4/top-headlines?country=pk&token=${API2}`
            let response = await fetchJsonp(url)
            let result = await response.json()
            
            console.log("News Data:", result)
                
                
        } catch (error) {
          console.log("error loading news data: ", error)  
        }
        
    }
    getNewsdata(props.country.trim())
    

},[])

CodePudding user response:

Resorting to JSONP is frowned upon nowadays; there are safer alternatives, such as CORS. Because the response's content type is application/json, using JSONP will not work anyway, because it causes Chrome's CORB feature to kick in.

Why not try to solve whatever CORS issue you seem to be having? I'd be very surprised if the API you're using weren't configured for CORS... A casual inspection of their documentation reveals that you're using the wrong domain, www.gnews.io, instead of gnews.io. The former redirects to the latter, but is not configured for CORS, which explains your CORS troubles.

Once you use the right domain (gnews.io), all your CORS troubles go away. And because there's no longer any need to reach for dirty tricks like JSONP, you can use good old reliable fetch rather than some third-party tool.

React.useEffect(()=> {
  async function getNewsdata(country){
    try {        
      let url = `https://gnews.io/api/v4/top-headlines?country=pk&token=${API2}` // gnews.io, not www.gnews.io
      let response = await fetch(url) // fetch, not fetchJsonp
      let result = await response.json()      
      console.log("News Data:", result)
    } catch (error) {
      console.log("error loading news data: ", error)  
    }     
  }
  getNewsdata(props.country.trim())
},[])
  •  Tags:  
  • Related