开发环境下:
我的是node与vuecli4.0搭建的页面 根目录下自行添加配置vue.config.js文件代码如下:
//vue.config.js
module.exports = {
// 基本路径
assetsDir: 'static', //build 打包
publicPath: './', //build 打包静态资源路径
devServer:{
proxy:{ //npm run build 打包后生成的是生产环境下的文件 此配置无效了!~
'/api':{ //接口标识 请求/api时等于请求 http://localhost:5050
target:"http://localhost:5050", //要代理后端接口地址
changeOrigin:true,
ws:true,
pathRewrite:{
'^/api':''
},
changeOrigin: true,//是否允许跨域
}
}
}
// 或者使用如下:
//devServer:{
// proxyTable: {
// '/api': {
// target: 'http://localhost:5050',
// changeOrigin: true,
// pathRewrite: {
// '^/api': '',
// }
// }
// },
// }
}
生产环境下:
可以去使用nginx反向代理。
也可以改变服务器代码,运行指定或任意地址访问:
这里 说明服务器端代码的修改:
app.all("*",function(req,res,next){
//设置允许跨域的域名,*代表允许任意域名跨域
res.header("Access-Control-Allow-Origin","*");
//允许的header类型
res.header("Access-Control-Allow-Headers","content-type");
//跨域允许的请求方式
res.header("Access-Control-Allow-Methods","DELETE,PUT,POST,GET,OPTIONS");
if (req.method.toLowerCase() == 'options')
res.send(200); //让options尝试请求快速结束
else
next();
})