跨域配置
文档:https://www.npmjs.com/package/egg-cors
安装:npm i egg-cors --save
配置插件
// {app_root}/config/plugin.js
exports.cors = {
enable: true,
package: 'egg-cors',
};
config/config.default.js 目录下配置
config.security = {
// 关闭 csrf
csrf: {
enable: false,
},
// 跨域白名单
domainWhiteList: [ 'http://localhost:3000' ],
};
// 允许跨域的方法
config.cors = {
origin: '*',
allowMethods: 'GET, PUT, POST, DELETE, PATCH'
};
egg-cors 插件基于 @koa/CORS。
egg-cors
works internally with egg-security. By defining the property of domainWhiteList
on object security
, you have successfully informed the framework to whitelist the passed domains.
When you make a request from client side, egg should return an Access-Control-Allow-Origin
response header with the domain that you passed in along with the payload and status code 200.
exports.security = { domainWhiteList: [ 'http://localhost:4200' ], };
Configuration
Support all configurations in @koa/cors.
// {app_root}/config/config.default.js exports.cors = { // {string|Function} origin: '*', // {string|Array} allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH' };
If the origin
is set, the plugin will follow it to set the Access-Control-Allow-Origin
and ignore the security.domainWhiteList
. Otherwise, the security.domainWhiteList
which is default will take effect as described above.
Security
当安全插件启用时,只有在安全域列表支持 CORS 跨域。