在接口联调时,由于项目本地运行地址是***.*.*:1000(或localhost:1000 假设),接口服务的地址是***.*.*:2000(假设)
而1000调用接口的2000,产生了跨域的问题,就是本地代理没有同域名,导致的跨域问题。
场景:用create-react-app 脚手架搭建了一个新的项目,联调时出现的跨域问题。报了Access to XMLHttpRequest .......... 错误。
以下是解决方式:
1.安装http-proxy-middleware
npm install --save http-proxy-middleware
2.在src目录下新建一个setupProxy.js文件。(可以在文件中配置多个接口服务)内容如下
const { createProxyMiddleware } = require("http-proxy-middleware");
module.exports = function (app) { // 可配置多个接口服务
app.use( // 假设接口地址:http://***.*.*.*:2000/api/dome?act=test
createProxyMiddleware("/api", { // iceApi是自定义的,用的时候也要对应写iceApi
target: 'http://***.*.*.*:2000', // 请求的地址(接口的)
changeOrigin: true,
pathRewrite: {
"^/api": "/api"
}
})
);
app.use( // 假设接口地址:http://***.*.*.*:3000/api888/dome?act=test
createProxyMiddleware("/api888", { // iceApi是自定义的,用的时候也要对应写iceApi
target: 'http://***.*.*.*:3000', // 请求的地址(接口的)
changeOrigin: true,
pathRewrite: {
"^/api888": "/api888"
}
})
);
}
调用时:
// 列表
const getDataList = async () => {
try {
const res = await axios.post(`/api/dome?act=test`, {参数});
setDataList(res.data);
}catch (error) {
console.log(error, '---');
}
};
这样就可以解决本地代理没有同域名的跨域问题了。