samedi 26 mai 2018

Node JS Express Server - Cross Origin Request Blocked, even with all the correct headers

Despite having the correct headers in my nodejs server:

app.get('/api', function(req, res){
    res.header('Access-Control-Allow-Origin'. '*');
    res.header('Access-Control-Allow-Methods', 'GET');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');

    res.status(200).send({'a':'b'});
});

When I make requests in my firefox browser, I still get the error:

"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://www.example.com/api/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)."

This is how I make the request on the client side:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
    if(this.readyState === 4 && this.status === 200){
        console.log(this.response);
    }
};
xhr.open('GET', 'http://www.example.com/api', true);
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET');
xhr.setRequestHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
xhr.send(null);




Aucun commentaire:

Enregistrer un commentaire