CORS express not working predictably

前端 未结 6 1027
灰色年华
灰色年华 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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-08 08:33

    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) {
      ...
    });
    

提交回复
热议问题