【问题标题】:express runs into The 'Access-Control-Allow-Origin' header has a value 'http://mydomain.local:5173/' that is not equal to the supplied originexpress 运行到 The \'Access-Control-Allow-Origin\' header has a value \'http://mydomain.local:5173/\' that is not equal to the supplied origin
【发布时间】:2022-11-17 02:24:46
【问题描述】:

我有一个简单的提取:

   fetch('http://mydomain.local:5000/auth', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*',
    'access-control-allow-credentials' : true
  },
  body: JSON.stringify({ 
    username : "admin",
    password : "123"
  })
})
  .then((response) => response.json())
  .then((data) => {
    console.log('Success:', data);
  })
  .catch((error) => {
    console.error('Error:', error);
  });
   }

连接到后端:

app.use(cors({credentials: true, origin: 'http://mydomain.local:5173/'}));
app.all('/*', function(req, res, next) {
          res.header('Access-Control-Allow-Origin', req.headers.origin || "*");
          res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,HEAD,DELETE,OPTIONS');
          res.header('Access-Control-Allow-Headers', 'content-Type,x-requested-with'); 
          next();
});

但我得到:

Access to fetch at 'http://mydomain.local:5000/auth' from origin 'http://mydomain.local:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'http://mydomain.local:5173/' that is not equal to the supplied origin. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

我试图通过启用原点并上下移动 cors 来绕过它,但我找不到绕过它的方法。我该如何解决这个问题?

【问题讨论】:

    标签: node.js express


    【解决方案1】:

    我想你有这个问题是因为你没有在你的项目中安装cors。

    尝试:

    npm install cors
    

    在这之后尝试在你的文件中需要cors:ex。

    var express = require('express')
    var cors = require('cors')
    var app = express()
    
    app.use(cors())
    
    app.get('/products/:id', function (req, res, next) {
      res.json({msg: 'This is CORS-enabled for all origins!'})
    })
    
    app.listen(80, function () {
      console.log('CORS-enabled web server listening on port 80')
    })
    

    我在 site of express 的 cors 文档中找到了这个解决方案

    【讨论】:

      猜你喜欢
      • 2013-12-11
      • 2021-04-28
      • 1970-01-01
      • 2019-01-18
      • 2016-07-10
      • 1970-01-01
      • 2022-08-08
      • 2013-10-25
      • 2017-12-01
      相关资源
      最近更新 更多