CORS express not working predictably

2020-06-16 03:17发布

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

6条回答
ら.Afraid
2楼-- · 2020-06-16 03:21

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)
});
查看更多
叼着烟拽天下
3楼-- · 2020-06-16 03:27

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');
查看更多
戒情不戒烟
4楼-- · 2020-06-16 03:30

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) {
  ...
});
查看更多
孤傲高冷的网名
5楼-- · 2020-06-16 03:39

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.

查看更多
够拽才男人
6楼-- · 2020-06-16 03:39

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())
查看更多
迷人小祖宗
7楼-- · 2020-06-16 03:45

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

...
查看更多
登录 后发表回答