1、成因:
浏览器同源策略,即协议,域名,端口都相同就是同源。当请求地址中任一项与前端服
务中的上述项出现不一致时,便会出现跨域问题。
2、解决方案
- vue.config.js中配置代理
module.exports = {
publicPath: "./",
// outputDir: "dist",
assetsDir: "assets",
devServer: {
port: 9000,
host: "localhost",
https: false,
hotOnly: false,
open: true,
proxy: {
"/api": {
target: " http://localhost:3000 ", //需要跨域的目标url
changeOrigin: true, // 将基于名称的虚拟托管网站的选项,如果不配置,请求会报404
ws: true,
}
}
}
}
- 服务端node.js配置
server.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 , yourHeaderFeild');
res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
if (req.method == 'OPTIONS') {
res.send(200);
}
else {
next();
}
});
仅作为个人笔记!!!