CORS express not working predictably

前端 未结 6 1154
灰色年华
灰色年华 2021-02-08 08:15

I am trying to allow access from everywhere.

I have tried using app middleware:

app.use(function (req, res, next) {
  res.setHeader(\"Access-Control-Allo         


        
6条回答
  •  忘掉有多难
    2021-02-08 08:55

    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.

提交回复
热议问题