- 创建代理配置文件
在src下创建文件: src/setupProxy.js
- 编写setupProxy配置具体规则:
const proxy = require('http-proxy-middleware')
module.exports = function (app) {
app.use(
proxy('/api1', { // 遇见/api1前缀的请求会触发该代理配置
target: 'http://localhost:5000', // 请求转发给谁
// changeOrigin: true, // 默认值 false 控制服务器收到的响应头中host字段的值 加上req.HOST值localhost:5001 不加是localhost:3000 最好加上
// pathRewrite: {'^/api1': '' } // 重写请求路径 不加是 /api1/students 加上是 /students
}),
proxy('/api2', {
target: 'http://localhost:5001',
changeOrigin: true,
pathRewrite: {'^/api2': '' }
})
)
}
import axios from 'axios'
import React, { Component } from 'react'
export default class App extends Component {
getStudentData = () => {
axios.get('http://localhost:3000/api1/students').then(res => {
console.log('成功', res.data )
}, err => {
console.log('失败', err)
})
}
getCarData = () => {
axios.get('http://localhost:3000/api2/cars').then(res => {
console.log('成功', res.data )
}, err => {
console.log('失败', err)
})
}
render() {
return (
<div>
App....
<button onClick={this.getStudentData}>点我获取数据</button>
<button onClick={this.getCarData}>点我获取骑车数据</button>
</div>
)
}
}
server1 :5000
const express = require('express')
const app = express()
app.use((req,res, next) => {
console.log("有请求")
console.log(req.get('Host'))
console.log('地址',req.url)
next()
})
app.get('/students', function (req, res) {
const students = [
{id: 001, name: 'tom',age:18},
{id: 002, name: 'jerry',age:19},
{id: 003, name: 'tony',age:120},
]
res.send(students)
})
app.listen(5000, () => console.log('Example app listening on port 5000!'))
server2 5001
const express = require('express')
const app = express()
app.use((req,res, next) => {
console.log("有请求")
console.log(req.get('Host'))
console.log('地址',req.url)
next()
})
app.get('/cars', function (req, res) {
const cars = [
{id: 001, name: '奔驰',price:199},
{id: 002, name: '马自达',price:109},
{id: 003, name: '捷达',price:120},
]
res.send(cars)
})
app.listen(5001, () => console.log('Example app listening on port 5001!'))
网友评论