user3818284
user3818284

Reputation:

How is the CORS "Access-Control-Allow-Origin" value exposed to the browser?

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

Answers (1)

waTeim
waTeim

Reputation: 9235

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.

Upvotes: 3

Related Questions