如何在Node.js应用程序中使用CORS修复此错误

时间:2019-10-22 04:56:34

标签: node.js express axios

我在fe中有以下代码:

  getTasks = () => {
    axios.get("http://127.0.0.1:3000/api/getTasks", {
      withCredentials: true
    }).then(response => {
      console.log(response)
    })
  }

,此代码为:

var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());

app.use(function (req, res, next) {
  res.header('Access-Control-Allow-Origin', req.header('origin'));
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.header("Access-Control-Allow-Credentials: true");
  next();
});

当用户登录并请求getTasks()时,出现此错误:

Access to XMLHttpRequest at 'http://127.0.0.1:3000/api/getTasks' from origin 'http://localhost:3002' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

3 个答案:

答案 0 :(得分:0)

您可以为此使用npm CORS

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

// other stuff

答案 1 :(得分:0)

可能是您没有正确设置属性。

尝试:res.header("Access-Control-Allow-Credentials", "true");

答案 2 :(得分:-1)

您可以在enable-cors website上了解有关CORS的更多信息,还有ExpressJS的示例CORS代码。

在node.js上的ExpressJS应用中,对路由执行以下操作:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "YOUR-DOMAIN.TLD"); // update to match the domain you will make the request from
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.header("Access-Control-Allow-Credentials", "true")
  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
});