1

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?

  • It's sent as a header, just as usual. What makes you think the request is avoided? There should be a preflight request, though. – Bergi Jul 13 '14 at 22:54
  • Enjoy the read: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS – epascarello Jul 13 '14 at 23:08
  • @Bergi The request's processing never seems to initiate if the browser throws the no "Access-Control-Allow-Origin" header error. –  Jul 13 '14 at 23:33
  • @epascarello it was certainly a thrilling read.. –  Jul 14 '14 at 00:37

1 Answers1

3

This question has come up many times, but perhaps bears emphasis

  1. For non simplistic queries, browsers send an OPTIONS message preflight as described here and asked specifically in this question. You app is not responding to the OPTIONS message the browser is sending and so CORS is not enabled subsequently.
  2. For specifically how to intercept the OPTIONS message in the context of a node.js server see here and here
  3. Additionally, when using jQuery to access your site, you'll need to construct the headers and if you're dealing with HTTP Auth, then you can not accept '*'. It appears you are dealing with login type verbs.
Community
  • 1
  • 1
waTeim
  • 9,095
  • 2
  • 37
  • 40