Lin Du
Lin Du

Reputation: 102267

`fetch`, work with mode `no-cors` does not call the promise.then callback

Here is my code snippet:

const url = util.API + '/ip/ip2addr' + `?ip=${this.state.ip}&key=${util.appKey}`;

 fetch(url, {mode: 'no-cors'}).then(res => res.json()).then(data => {
     //does not call this callback
     this.setState({res: data.result});
 }).catch(err => {

 });

I saw the response, but not call the promise.then method, why? how can I get the response data?

It seems third-party api do not support CORS, so, my think is to write a node server.

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

app.use(bodyParser.json());
app.use(bodyParser.urlencoded(extended: true)); 

app.get('/ip/ip2addr', (req, res) => {
    const url = util.API + '/ip/ip2addr' + `?ip=${ip}&key=${appKey}`;

    request
    .get({url}, (err, response, body) => {
        if (!err && response.statusCode == 200) {
            res.json(body);
        }
    })

});

app.listen(port, err => {
    if(err) throw err;
    console.log(`Server is listen on port ${port}`);
});

After search and read some articles, I think webpack-dev-server proxy settings will solve this problem too.

Upvotes: 0

Views: 3324

Answers (1)

Freyja
Freyja

Reputation: 40804

MDN has an explanation why your code doesn't work:

no-cors — Prevents the method from being anything other than HEAD, GET or POST. If any ServiceWorkers intercept these requests, they may not add or override any headers except for these. In addition, JavaScript may not access any properties of the resulting Response. This ensures that ServiceWorkers do not affect the semantics of the Web and prevents security and privacy issues arising from leaking data across domains.

Basically, you a no-cors request results in an opaque response, that which JavaScript code cannot read. You're allowed to make the request, but you still can't circument CORS.

While you can't read from these responses, one use case for no-cors is service workers, which may intercept want to intercept requests from different origins (for instance, when an <img /> loads), e.g., for caching. (Jake Archibald explains a bit about this here)

Upvotes: 2

Related Questions