webpack 4+ create-react-app如何配置请求跨域
一、安装http-proxy-middleware管理包,npm i --save http-proxy-middleware
二、在项目目录src/下新建setupProxy.js文件,然后写入如下代码:
const proxy = require(‘http-proxy-middleware‘);
module.exports = function(app) {
app.use(proxy(‘/api‘, {
target: ‘http://localhost:8090‘ ,
secure: false,
changeOrigin: true,
pathRewrite: {
"^/api": "/"
},
// cookieDomainRewrite: "http://localhost:3000"
}));
};
三、然后设置axios默认前缀 axios.defaults.baseURL = ‘/api’;
发送axios请求
axios('/getDailyAims').then(res => {
console.log(res);
})