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

Node.js 如何在nodejs应用程序中使用CORS修复此错误,node.js,express,axios,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({ ext

我在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.
您可以使用npm进行此操作


您可以在上了解有关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
});

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


Try:
res.header(“访问控制允许凭据”,“true”)

可能重复的可能重复的可能重复的不它不是重复的-请再次阅读问题@马克斯
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
});