3

I have a very simple nodejs server, but using the 'cors' package seems to not recognize the origin of the request for some reason.

Here is my nodejs server config:

const cors = require('cors');
const express = require('express');

const CORS_WHITELIST = [ 'http://localhost:5000' ];

const corsOptions = {
  origin: (origin, callback) => {
    console.log(origin) // ----> this is always 'undefined'
    if (CORS_WHITELIST.indexOf(origin) !== -1){
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
    }
  }
};

const configureServer = app => {
    app.use(cors(corsOptions));
};

module.exports = configureServer;

Here is my server starter file:

const express = require('express');

const SERVER_CONFIGS = require('./constants/server');

const configureServer = require('./server');
const configureRoutes = require('./routes');

const app = express();

configureServer(app);
configureRoutes(app);

app.listen(SERVER_CONFIGS.PORT, error => {
  if (error) throw error;
  console.log('Server running on port: ' + SERVER_CONFIGS.PORT);
});

I am running this server on localhost, but the origin in the cors callback is always 'undefined'. For example when I open http://localhost:5000 on the browser or do a curl call.

How can I use cors so that it doesn't block the request on localhost?

user2212461
  • 3,105
  • 8
  • 49
  • 87

1 Answers1

4

I read this issue and req.headers.origin is undefined question and also CORS and Origin header!

source:

The origin may be hidden if the user comes from an ssl encrypted website.

Also: Some browser extensions remove origin and referer from the http-request headers, and therefore the origin property will be empty.

There is a solution to solve this by adding a middleware:

app.use(function (req, res, next) {
  req.headers.origin = req.headers.origin || req.headers.host;
  next();
});

I hope these helps. The issue is in awaiting more info state!

Community
  • 1
  • 1
Saeed
  • 5,413
  • 3
  • 26
  • 40
  • 1
    Same problem. This solution worked but I recently see a different approach. Are both solutions equals or one is best secured? `if (CORS_WHITELIST.indexOf(origin) !== -1 || !origin){ ..... }` – Keitaro Mar 14 '23 at 16:29