外部应用访问Egg搭建的页面,Egg解决跨域访问
Egg配置
直接上代码,假如我当前Egg搭建的服务,其域名是:http://hello.world.com
。外部应用想要通过iframe
等方式嵌套这个域名下的页面,Egg
则需要配置一些信息。
Egg
在config.default.ts
文件中添加以下配置:
export default (appInfo: EggAppInfo) => {
config.security = {
csrf: {
enable: false,
},
csp: {
enable: true,
policy: {
'frame-ancestors': 'self hello.world.com'
},
}
};
}
解释如下:
csrf
:enable
为false
则代表关闭默认的安全系统。csp(Content Security Policy)
:enable
为true
就是开启。frame-ancestors
:一个HTTP
响应头,用于控制页面是否允许被嵌套在iframe
中。该响应头可以指定一个或多个允许嵌套当前页面的域名或URL
,或者设置为'none'
,表示不允许任何页面嵌套当前页面。- 上面的
'self'
表示同域名下的页面,以及我们的hello.world.com
域名,开启后,就可以外部通过iframe
嵌套跨域访问了。