产生跨域的原因:
同域是:协议、域名、端口号相同,不会产生跨域
http://baidu.com ----协议http、域名baidu、默认端口:80
https://baidu.com ----协议https、域名baidu、默认端口:443
上面两个就存在跨域问题
1.proxy代理【前端】
proxy: {
"/api": {
target: "http://localhost:3000",
pathRewrite:{"/api":""}
}
}
2.cors【后端】
var allowCrossDomain = function (req, res, next) {
// 请求源 ajax http://localhost:8080
res.header("Access-Control-Allow-Origin", "*");
// 请求头 x-token
res.header("Access-Control-Allow-Headers", "*");
// 请求方法 post get put delete patch
res.header("Access-Control-Allow-Methods", "*");
// 下一步
next();
}
app.use(allowCrossDomain);
3.中间件
let webpack = require("webpack");
let middle = require("webpack-dev-middleware");
let compiler = webpack(require("./webpack.config"));
app.use(middle(compiler));