解决前端跨域问题合集
中间件:
node.js中解决前端跨域问题的成熟方案:
/*解决跨域问题*/
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
res.header("X-Powered-By",' 3.2.1')
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
前端页面(uni-app)
配置uni-app 中 manifest.json->h5->devServer即可
manifest.json
"h5" : {
"devServer" : {
"https" : false,
"port" : 8080,
"proxy" : {
"/apis" : {
"target" : "http://v.juhe.cn",
"changeOrigin" : true,
"secure" : false,
"pathRewrite" : {
"^/apis" : ""
}
}
}
}
}
前端页面请求:
axios({
url:'/apis/toutiao/index?type=&page=&page_size=&key=e0a7cd9c6baa43d5e78d923aaed24d32',
Method:'get'
}).then(response=>{
console.log(result.data)
this.data=result.data;
}).catch((Error)=>{
})
需要在根目录上创建一个vue.config.js文件
// vue.config.js,也可以在mainifest.json中配置跨域,但是只能配一处
module.exports = {
devServer: {
proxy: {
'/apis': {
target: 'http://v.juhe.cn',
pathRewrite: {
'^/apis': '' // 设置/api路径重定向,重点!!!
}
}
},
}
}