RockSAMA RockSAMA - 1 month ago 5
Javascript Question

Request were sent successfully,but return an empty promise when use 'fetch'

I worked with React and fetch to send a request like:

fetch(`http://www.bilibili.com/index/catalogy/1-3day.json`,{
mode: "no-cors"
}).then(r => r.json()).then(r => {
console.log(r);
}).catch(err => {console.log(err);})


and the response is right in the network tab

but it throw an error that:

SyntaxError: Unexpected end of input
at SyntaxError (native)
at http://127.0.0.1:8888/js/video.bundle.js:30174:15


And when I try to log the promise,it appears to be an strange Object:

Response {type: "opaque", url: "", status: 0, ok: false, statusText: ""…}


this is the picture

Can someone help? I'm really confused with this

Answer

You cannot make requests to external servers that do not support cross origin resource sharing (CORS).

By setting the no-cors mode on the request, you explicitly tell the server to make the request for side effects without being able to access its content. This is similar to when you place an <img> tag in your HTML from a third party site and can't access its contents - it's opaque to the calling code.

You need to download that json on the server side and then serve it from your own server to avoid the issue.