Reputation:
In Node.js, I understand the syntax for sending an "Access-Control-Allow-Origin" value in the response header, but I'm confused as to how the heck this value is exposed to the browser before being processed by the server, since the response header is decided later, after processing the request, when the response is actually sent.
For example, with Express:
/* Server */
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.post('/login', function (req, res) {
var username = req.body.username;
var password = req.body.password;
if (username !== "undefined"){
respondSuccess(req,res);
} else {
respondFailure(req,res);
}
});
app.listen(2222);
Here, whether or not there is a "Access-Control-Allow-Origin" header or not depends on the result of the username being undefined or not.
function respondSuccess(){
body = "Success!";
res.writeHead(200, {
'Access-Control-Allow-Origin' : '*',
'Content-Length' : body.length,
'Content-Type' : 'text/html'
});
res.write(body);
res.end();
}
function respondFailure(){
body = "Failure!";
res.writeHead(200, {
'Content-Length' : body.length,
'Content-Type' : 'text/html'
});
res.write(body);
res.end();
}
But the web browser seems to completely avoid sending the request if it does not detect that "Access-Control-Allow-Origin" header matching the source.
How is the CORS "Access-Control-Allow-Origin" value exposed to the browser in Node.js?
Upvotes: 1
Views: 2570
Reputation: 9235
This question has come up many times, but perhaps bears emphasis
Upvotes: 3