浏览器跨域问题及常用解决方法
2021-08-01 本文已影响0人
弹力盒
1、跨域定义
只要协议、域名、端口有任何一个不同,都被当作是不同的域,前端跨域是浏览器特有的一种安全策略
2、作用范围
跨域是浏览器特有的一种安全机制,后端服务等不存在跨域情况
3、解决方案
- a、后端设置响应头的 Access-Control-Allow-Origin 属性
// 全局拦截所有请求,做相关的操作
app.all('*', (req, res, next) => {
if (req.method === 'OPTIONS') {
return false;
}
// 支持跨域
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type');
res.header('Access-Control-Allow-Methods', '*');
res.header('Content-Type', 'application/json;charset=utf-8');
next();
});
- b、前端通过代理的方式请求接口,如 webpack 的 devServer
devServer: {
before: function (app, server, compiler) {
/* mock 接口 */
app.get('/api/demo', (req, res) => {
setTimeout(() => {
res.send({
data: 'something...'
})
}, 5000)
})
},
proxy: {
'/api': {
/*
* 将来自 http://localhost:8000/api
* 的请求资源全部转发为 /api开头的请求
*/
target: 'http://localhost:8000/api',
changeOrigin: true,
secure: false,
pathRewrite: {
'^/api': ''
}
},
'/tools': {
/*
* 将来自 http://www.tanglihe.cn/tools
* 的请求资源全部转发为 /tools开头的请求
*/
target: 'http://www.tanglihe.cn/tools',
changeOrigin: true,
secure: false,
pathRewrite: {
'^/tools': ''
}
}
}
}
- c、JSONP 请求数据(JSONP 只支持 GET 请求)