Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

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

问题描述

前端用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',
  };

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...