一、在src
下新建setupProxy.js
文件
不要乱起名字,一定要是这个文件名
- 安装
http-proxy-middleware
插件
yarn add http-proxy-middleware
//setupProxy.js
const {
createProxyMiddleware
} = require('http-proxy-middleware')
module.exports = function (app) {
app.use('/api1',
createProxyMiddleware({
target: 'http://localhost:3001', //配置转发目标地址
changeOrigin: true, //控制服务器接收到的请求头中host字段的值
pathRewrite: {
'^/api1': ''
} //去除请求前缀址(必须配置)
}),
),
app.use('/api2',
createProxyMiddleware({
target: 'http://localhost:3002',
changeOrigin: true,
pathRewrite: {
'^/api2': ''
}
}),
)
}
二、跨域演示
//app.js
import { useState } from "react";
import { http } from './utils/http';
function App() {
// 声明一个新的叫做 “count” 的 state 变量
const [count, setCount] = useState(0);
const add = async (res) => {
setCount(count + res)
}
const getData1 = async () => {
let getData = await http.get('/api1/stu')
console.log(getData.data);
}
const getData2 = async () => {
let getData = await http.get('/api2/stu')
console.log(getData.data);
}
return (
<div className="App">
<p>You clicked {count} times</p>
<button onClick={ () => add(1)}>
Click me
</button>
<hr />
<button onClick={ () => getData1()}>
从3001端口请求数据
</button><button onClick={ () => getData2()}>
从3002端口请求数据
</button>
</div>
);
}
export default App;
//http.js
import axios from 'axios'
const http = axios.create({})
export {
http
}
三、服务端代码
//app.js
const express = require('express')
const app = express()
app.get('/stu', ( req, res ) => {
res.send('3001端口请求回来的数据')
res.end()
})
app.listen(3001, () => {
console.log('3001端口服务启动成功');
})
//server.js
const express = require('express')
const app = express()
app.get('/stu', ( req, res ) => {
res.send('3002端口请求回来的数据')
res.end()
})
app.listen(3002, () => {
console.log('3002端口服务启动成功');
})