在src文件夹下新建文件setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'https://xxx.xxx.xx',
changeOrigin: true,
pathRewrite:{
'^/api':''
}
})
);
};
/**
* 1.遇见/api前缀的请求,就会触发代理配置
* 2.target:请求转发给谁
* 3.changeOrigin:控制服务器收到的请求头中Host的值
* 4.pathRewrite:重写请求路径(必须)
*/
案例
组件请求:
import { useEffect } from 'react';
import axios from 'axios';
function App() {
useEffect(() => {
axios
.get('/api/search/users?q=sun')
.then((res) => {
console.log(res.data);
})
}, [])
return (
<div>
app
</div>
);
}
export default App;
代理配置:
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'https://api.github.com',
changeOrigin: true,
pathRewrite:{
'^/api':''
}
})
);
};
运行结果: