下面我们写一个例子,用户点击按钮请求后台获取学生信息,请求的url就是上一篇中的localhost:5000/student
1 在packages.json中配置代理
我们用create-react-app脚手架新建一个项目
下载axios依赖
cnpm install axios
修改App.js
import React, { Component } from 'react';
import './App.css'
import axios from 'axios'
class App extends Component {
getStudentData = ()=>{
axios.get('http://localhost:3000/student').then(
response => {console.log('成功了',response.data)},
error => {console.log('失败了',error)}
render() {
return (
<button onClick={this.getStudentData}>点我获取学生数据</button>
export default App;
然后,修改package.json,添加:
"proxy": "http://localhost:5000"
,然后启动上一节中的express后台。并启动本项目,
2 setupProxy.js配置多个代理
我们删除package.json中配置的代理。
在src目录下新建setupProxy.js文件
const proxy = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
proxy('/api1',{
target: 'http://localhost:5000',
changeOrigin:true,
pathRewrite:{'^/api1':''}
proxy('/api2',{
target: 'http://localhost:5001',
changeOrigin:true,
pathRewrite:{'^/api2':''}
修改App.js
import React, { Component } from 'react';
import './App.css'
import axios from 'axios'
class App extends Component {
getStudentData = ()=>{
axios.get('http://localhost:3000/api1/student').then(
response => {console.log('成功了',response.data)},
error => {console.log('失败了',error)}
getCarData = ()=>{
axios.get('http://localhost:3000/api2/car').then(
response => {console.log('成功了',response.data)},
error => {console.log('失败了',error)}
render() {
return (
<button onClick={this.getStudentData}>点我获取学生数据</button>
<button onClick={this.getCarData}>点我获取汽车数据</button>
export default App;
当请求以/api1开头则代理把请求转发给localhost:5000
当请求以/api2开头则代理把请求转发给localhost:5001
但是运行后,页面一直报 GET http://localhost:3000/api1/student 404 (Not Found) 。暂时未解决。