最近create-react-app在"package.json"的"proxy"中不再支持写object只支持字符串了,那么我们该如何配置proxy呢?
1、安装http-proxy-middleware:
yarn add http-proxy-middleware
2、在'src'目录下新建'setupProxy.js'并写入:
const proxy = require('http-proxy-middleware');
module.exports = function (app) {
app.use(
proxy(
'/index',
{
target: 'https://www.bilibili.com',
changeOrigin: true
}
)
);
};
3、重新启动服务,在测试组件中加入:
componentDidMount = () => {
axios.get('/index/recommend.json')
.then((res) => {
console.log(res.data.list);
})
};
如果之前有多个,那么就多写几个对应的app.use();
解决报错“proxy is not a function”:
// 引入方式变为:
const {createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function (app) {
app.use(
// 将原来的proxy改为createProxyMiddleware
createProxyMiddleware(
'/index',
{
target: 'https://www.bilibili.com',
changeOrigin: true
}
)
)
};