1、从后端解决
下面是用node解决的方案
在express中,在app.js中加入
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By",' 3.2.1')
if(req.method=="OPTIONS") res.send(200);/*让options请求快速返回*/
else next();
});
在koa中,可以引入koa-cors
const cors = require('koa-cors');
app.use(cors());
2、从前端解决
下面是vue解决的方案,拿vue-cli3举例,在vue.onfig.js里面加入devServer
devServer: {
proxy: {
'': {
target: 'http://localhost:3000',
changeOrigin: true,
ws: true
}
}
},
以上是在开发过程中解决的方法,打包之后这样接口就会调用失败,显示404
所以在打包之后还需要再nginx中配置代理
location / {
proxy_set_header Host $host;
proxy_set_header x-forwarded-for $remote_addr;
proxy_set_header X-Real-IP $remote_addr;
proxy_pass http://127.0.0.1:3000; // 接口地址,如果在同一个服务器上,可以直接这样写
}