0

This probably may be a duplicate question, but I'm not able to do this correctly.

I have enabled CORS in my backend (reading this). But, still, when I try to hit an API on my API server through my UI server, I get this:

Request header field Authentication is not allowed by Access-Control-Allow-Headers in preflight response.

Here are some relevant parts of my code:

Backend

// enable CORS
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();
});

Frontend

$.ajax({
    method: 'GET',
    url: ...,
    headers: {
        Authentication: ...
    },
    ...
});
Anubhav Dhawan
  • 1,431
  • 6
  • 19
  • 35
  • Put `Authentication` in your `res.header` http://stackoverflow.com/questions/25727306/request-header-field-access-control-allow-headers-is-not-allowed-by-access-contr – abdulbarik Sep 27 '16 at 10:16

2 Answers2

2

You need to allow that header explicitly

res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authentication");

And you'd better use some existing CORS module, as I'm not sure your implementation is 100% correct.

I use this CORS middleware:

function (req, res, next) {
    // CORS headers
    res.header("Access-Control-Allow-Origin", YOUR_URL); // restrict it to the required domain
    res.header("Access-Control-Allow-Methods", "GET,PUT,PATCH,POST,DELETE,OPTIONS");
    // Set custom headers for CORS
    res.header("Access-Control-Allow-Headers", YOUR_HEADER_STRING);

    if (req.method === "OPTIONS") {
        return res.status(200).end();
    }

    return next();
};
Anubhav Dhawan
  • 1,431
  • 6
  • 19
  • 35
Vsevolod Goloviznin
  • 12,074
  • 1
  • 49
  • 50
  • Can you suggest me what I could have improved? I think the only thing I'm doing wrong right now is by setting `Access-Control-Allow-Origin` as `*` – Anubhav Dhawan Sep 27 '16 at 11:43
  • @AnubhavDhawan take a look at this cors module for example: https://github.com/expressjs/cors. I will add the code that I use that takes pre-flight requests into account – Vsevolod Goloviznin Sep 27 '16 at 11:45
1

I would like to recommend you to use express cors module like

var cors = require('cors');


// enable CORS
app.use(cors());

and do not forgot to install

npm install cors --save
Arif Khan
  • 5,039
  • 2
  • 16
  • 27