前言
Access to XMLHttpRequest at 'http://localhost:3000/XXX/XXX' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

跨域问题是入门学习时经常遇到的问题,以前让后台的同学允许跨域,但是当项目比较庞大时,让后端的同学去允许跨域是相对麻烦的,本文介绍前端使用webpack devServer解决跨域的方法。
原理说明
使用webpack.devServer解决跨域的原理就是我们将请求发给webpack dev server,由webpak dev server向api地址发送请求,流程图如下

原理非常简单,如此一来在开发环境下就可以解决跨域问题了。
本文使用axios发送Ajax请求
接下来我们看看如何进行配置
webpack.devServer配置及发送请求
假设我们现在要请求的接口为
http://localhost:3000/post_data
POST
{
data:"test"
}
在webpack配置,devServer下添加proxy
devServer: {
hot: true,
host: "localhost",
port: 8080, //本地localhost端口
historyApiFallback: true,
proxy: { //设置代理
"/dev_api": {
target: "http://localhost:3000",
pathRewrite: { "^/dev_api": "" },
changeOrigin: true
}
}
}
按照此例,当我们将请求发送给webpack devServer时,如果请求含有**/dev_api**,webpack devServer会代理请求至http://localhost:3000/,同时将"dev_api"置为""(pathRewrite),这样webpack devServer给localhost:3000发送请求就不会有错误了。
接下来发送请求
axios
.post("http://localhost:8080/dev_api/post_data", {//注意是发送至webpack devServer的本地localhost端口8080
data: "test"
})
.then(res => {
console.log(res);
}).catch((err)=>{
console.log(err);
})

我们可以看到Request URLhttp://localhost:8080/dev_api/post_data,webpack devServer代理请求返回结果
创建axios实例简化url
我们可以使用axios.create方法,传入baseURL简化url的写法,这样线上环境和开发环境只要修改创建实例时的baseURL值就可以了
const axiosInstance = axios.create({
baseURL:"http://localhost:8080/dev_api"
})
export default axiosInstance;
// xxx.js
import axiosInstance from "XXX/XXX/XXX/...";
// ...
axiosInstance
.post("/post_data", {
data: "test"
})
.then(res => {
console.log(res);
}).catch((err)=>{
console.log(err);
})
如此,开发环境和线上环境只需要改一个baseURL就可以了
参考资料
webpack-devServer.proxy
axios.create
Webpack dev server Proxy is not working - ReactJS