How to manage CORS policy properly in express?
Asked Answered
B

10

20

I am trying to allow access from everywhere.

I have tried using app middleware:

app.use(function (req, res, next) {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader('Access-Control-Allow-Methods', '*');
  res.setHeader("Access-Control-Allow-Headers", "*");
  next();
});

I have tried using it in the route:

app.post('/login',function(req,res){
var login   = req.body;
var sess    = req.session;

if (!login.email && !login.pwd){    
    return res.status(401);
}
res.header("Access-Control-Allow-Origin", '*');
res.header("Access-Control-Allow-Headers", '*');
.... more code here

Both do not work. I keep getting an error: "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."

Further down the server, we use similar code for another route, which works:

app.post('/questar',function(req,res){
//allow xhr post from retireup domains
var cors = {
    origin: "https://www.website.com";
};
res.header("Access-Control-Allow-Origin", cors.origin);
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.type('application/json');

I cannot tell the difference between the code, but only one set works. Any ideas why? This seems like an issue that shouldn't be so complicated. Thanks

Brutus answered 6/1, 2016 at 23:11 Comment(1)
try cors npm module ?Efficiency
U
15

MDN has a very short explanation on how a server should respond to a Preflight Request.

You handle CORS preflight requests by handling the HTTP OPTIONS method (just like you would handle GET and POST methods) before handling other request methods on the same route:

app.options('/login', ...);
app.get('/login'. ...);
app.post('/login'. ...);

In your case, it might be as simple as changing your app.use() call to app.options(), passing the route as the first argument, setting the appropriate headers, then ending the response:

app.options('/login', function (req, res) {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader('Access-Control-Allow-Methods', '*');
  res.setHeader("Access-Control-Allow-Headers", "*");
  res.end();
});
app.post('/login', function (req, res) {
  ...
});
Uranium answered 7/1, 2016 at 5:32 Comment(0)
T
26

After applying "cors" middleware. You should be passed "http://" before "localhost:". in url send to by Axios like this:

axios.get("http://localhost:8080/api/getData")
  .then(function (response) {
    this.items = response.data;
  })
  .catch(function (error) {
    console.log(error)
  });
Teflon answered 9/5, 2019 at 2:49 Comment(0)
U
15

MDN has a very short explanation on how a server should respond to a Preflight Request.

You handle CORS preflight requests by handling the HTTP OPTIONS method (just like you would handle GET and POST methods) before handling other request methods on the same route:

app.options('/login', ...);
app.get('/login'. ...);
app.post('/login'. ...);

In your case, it might be as simple as changing your app.use() call to app.options(), passing the route as the first argument, setting the appropriate headers, then ending the response:

app.options('/login', function (req, res) {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader('Access-Control-Allow-Methods', '*');
  res.setHeader("Access-Control-Allow-Headers", "*");
  res.end();
});
app.post('/login', function (req, res) {
  ...
});
Uranium answered 7/1, 2016 at 5:32 Comment(0)
J
10

Configure the CORS stuff before your routes, not inside them.

Here, like this (from enable-cors.org):

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

app.get('/', function(req, res, next) {
  // Handle the get for this route
});

app.post('/', function(req, res, next) {
 // Handle the post for this route
});

I always configure it like this in my Express+Angular apps and it works just fine.

Hope it helps.

Jacklight answered 7/1, 2016 at 5:27 Comment(1)
This should be highlighted, I was configuring my cors before the routes. Thanks alot, you saved me a lot of debug :DIlla
F
6

First install, the "cors" package from npm: npm i -S cors

Then enable it in your express server.

var express = require('express'),
  cors = require('cors');

const app = express();
app.use(cors());

...
Frenum answered 5/5, 2017 at 16:50 Comment(1)
Yes, do cors({origin: true}) instead of just cors()Rajput
D
4

All you have to whitelist the domains name to avoid getting cors error messages.

There is a plugin called cors, installed it into your project using this command

npm i cors

after installing use this code to remove the cors related errors form your project.

const cors = require('cors');

const corsOption = {
    credentials: true,
    origin: ['http://localhost:3000', 'http://localhost:80']
}

app.use(cors(corsOption));

In the origin section you can pass any domain to whitelist it. If you want to whitelist all the domain names, instead of passing the the urls array. you can pass '*' over there.

Example : origin: '*'

credentials: Configures the Access-Control-Allow-Credentials CORS header. Set to true to pass the header, otherwise it is omitted.

Danielldaniella answered 8/2, 2022 at 1:47 Comment(0)
S
3

Following some standard node projects out there, below CORS configuration worked for me always. It requires the npm package 'cors'. Note: Origin * means enabling responses to any origin and replies with status code 200. If this needs to be limited to one domain, update the origin accordingly. Ex: [origin: 'http://exampleui.com']

var cors = require('cors');
var corsOptions = {
    origin: '*',
    optionsSuccessStatus: 200,
  }
app.use(cors(corsOptions));
app.use(express.json())
Sydelle answered 9/4, 2020 at 19:45 Comment(1)
While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.Brittni
S
1

Still got stuck with this:

app.use(cors());

or this:

app.use(cors(
    origin: '*'
));

You should try this:

app.use(cors({
    credentials: true,
    origin: true
}));

Note: origin: '*' not this!!! and with credentials: true

Stephenstephenie answered 26/12, 2023 at 13:51 Comment(0)
L
0

Following other's answers, this worked for me:

res.setHeader("Access-Control-Allow-Origin", 'http://myDomain:8080');
res.setHeader('Access-Control-Allow-Methods', 'POST,GET,OPTIONS,PUT,DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type,Accept');
Lascivious answered 16/4, 2016 at 16:23 Comment(0)
E
0

This will do

import cors from 'cors';

....

app.use(cors(), express.json(), authMiddleware);
Equal answered 20/6 at 3:49 Comment(0)
B
-1

Express using middleware :

app.use(function (req, res, next) {
  const allowedOrigins = ["https://localhost:4002"];
  const origin = req.headers.origin;

  if (allowedOrigins.indexOf(origin) != -1) {
    res.header("Access-Control-Allow-Origin", origin);
  } else {
    res.header("Access-Control-Allow-Origin", "*");
  }
  res.header("Access-Control-Allow-Credentials", "true");
  res.header(
    "Access-Control-Allow-Methods",
    "GET, POST, OPTIONS, PUT, PATCH, DELETE"
  );
  res.header(
    "Access-Control-Allow-Headers",
    "Origin,Content-Type,Authorization,Accept,X-Requested-With,Cookie,User-Agent,Host,Referer"
  );
  res.header("Access-Control-Expose-Headers", "Content-Disposition");
  if ("OPTIONS" == req.method) {
    res.header("Access-Control-Allow-Methods", "PUT, POST, PATCH, DELETE, GET");
    res.sendStatus(200);
  } else {
    next();
  }
});

Express using cors NPM :

npm i --save cors 

in app.js

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

app.use(
  cors({
    origin: "*",
  })
);

Express with Typescript using cors NPM :

install npm dependencies :

npm i --save cors 
npm i --save-dev @types/cors

in app.js

import express, { Application, Request, Response } from "express";
import cors from "cors";

const app: Application = express();
app.use(cors({ origin: "*" }));
Brachyuran answered 20/6 at 5:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.