Search code examples
javascriptnode.jsexpresscorscross-origin-resource-policy

How to handle cors in express js? It works with the HTTP module but the origin in the header undefined in express js


I’m using the Express.js framework and trying to handle CORS, but req.headers.origin is returning undefined. I have a whitelist of allowed origins in my corsOptions, and I'm checking the origin in the headers. Why is the origin header coming back as undefined, and how can I fix it?

Here, what I'm trying.

const app = express();

const corsOptions = {
        origin: function (origin, callback) {
                // origin is undefined
                if (whitelist.indexOf(origin) !== -1) {
                        callback(null, true)
                } else {
                        callback("Not allowed by CORS")
                }
        },

        credentials: true, //access-control-allow-credentials:true
        optionSuccessStatus: 200,
        exposedHeaders: ['Content-Disposition']

}

process.env.NODE_ENV === "production" && app.use(helmet());

/**
 * Middleware
 */

app.use(cors(corsOptions));
app.use(express.json());
app.use(express.urlencoded({
        extended: true
}));
app.use(cookieParser());

app.disable('x-powered-by');

// Api
app.get("/test", (req, res) => {
        // req.headers.origin is undefined
        // req.header.get("origin") is undefined
        res.send("Response success");
});


Solution

  • Update: You do not need CORS (Cross-Origin Resource Sharing) for requests made to the same origin. They are allowed by default. So you can remove the middleware completely in case you need to allow only the same origin. All request from other origins will be blocked anyway.

    ===

    Ensure that the requests you’re testing include the Origin header: For instance, if you’re testing with a simple GET request from the same origin, the Origin header might not be included.

    If you do not want to block REST tools or server-to-server requests, add a !origin check in the origin function like so:

    const corsOptions = {
      origin: function (origin, callback) {
        if (whitelist.indexOf(origin) !== -1 || !origin) {
          callback(null, true)
        } else {
          callback(new Error('Not allowed by CORS'))
        }
      }
    }