CreateReactApp_React 配置跨域
方案A 通过 http-proxy-middleware
- 安装
http-proxy-middleware
依赖
yarn add http-proxy-middleware -S
根目录>src>setupProxy.js
:::details 点击查看代码
const {createProxyMiddleware}=require('http-proxy-middleware');
module.exports=function(app){
app.use(createProxyMiddleware('/api',{
target:'http://localhost:4000',
changeOrigin:true,
pathRewrite:{
'^/api':''
}
}));
}
:::
- 调用接口
:::details 点击查看代码
import axios from 'axios';
function findUser(){
axios.get('/api/user/list').then(res=>{
console.log(res);
});;
}
function App() {
return (
<div className="App">
<button onClick={findUser}>获取用户列表</button>
</div>
);
}
export default App;
:::