egg.js+axios怎么解决非简单请求跨域报错?

DDD7
  • 244

问题描述

前端用axios请求,后端用自己写的egg.js本机服务。post请求时报错.
图片.png

localhost/:1 Access to XMLHttpRequest at 'http://127.0.0.1:7001/admin/checkLogin' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.
10:37:12.595 xhr.js:177 POST http://127.0.0.1:7001/admin/checkLogin net::ERR_FAILED

相关代码

前端代码:

axios({
      method: 'post',
      url: 'http://127.0.0.1:7001/admin/checkLogin',
      data: dataProps,
      withCredentials: true,
      'Content-Type':'application/json;charset=UTF-8',
      "Access-Control-Allow-Credentials": true,
      "Access-Control-Allow-Headers":"Authorization,Origin, X-Requested-With, Content-Type, Accept",
      "Access-Control-Allow-Methods":"GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS"
    }).then(
      res => {}
    )

服务端config.default.js代码:

config.security = {
    crsf: {
      enable: false,
    },
    domainWhiteList: [ '*' ],
  };
config.cors = {
    origin: 'http://localhost:3000',
    credential: true, // 开启认证
    withCredentials: true,
    allowMethod: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS',
  };
评论
阅读 468
1 个回答
✓ 已被采纳

再次认真看了@koa/cors的文档,发现这个报错是自己把credentials拼错了,少写了一个s,刚接触node,见笑了。

撰写回答

登录后参与交流、获取后续更新提醒

宣传栏