eggjs 跨域访问
背景
因为前端项目是Vue构建,为了方便调试,故而设置可跨域访问。
步骤
1.添加插件 egg-cors。
npm i egg-cors -S
2.启用插件 egg-cors:
在 plugin.js 中:
exports.cors = {
enable: true,
package: 'egg-cors',
};
3.在config.default.js中配置:
config.security = {
csrf: {
enable: false,
},
// 配置白名单
domainWhiteList: [ 'http://localhost:8080' ],
};
config.cors = {
allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS',
};
以上即可。
但是有一个问题,这样设置后,session和cookie确实不见了。如果想要获取session和cookie可以在config.default.js添加配置:
config.cors = {
credentials: true,
allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS',
};
然后在发送跨域请求的时候附带参数:credentials = true,
比如我用的 flyio,做的网络请求可以这样:
// 设置拦截器
fly.interceptors.request.use((request)=>{
// 以下两种均可
// request.withCredentials = true;
request.body.credentials = true;
return request;
});
其他框架也是如此,只要添加添加该请求参数即可。