egg.js+axios怎么解决非简单请求跨域报错?
问题描述
前端用axios请求,后端用自己写的egg.js本机服务。post请求时报错.
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',
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
再次认真看了
@koa/cors
的文档,发现这个报错是自己把credentials
拼错了,少写了一个s,刚接触node,见笑了。