React配置代理解决跨域问题

一、在src目录下建立setupProxy.js, 使用CJS(common JS)语法配置代理,适合一个或多个代理

const proxy = require('http-proxy-middleware')

module.exports = function(app){
    app.use(//传入一个或多个代理proxy,以逗号隔开
        // 前缀、
        proxy('/api1', {
            target: 'http://localhost:5000',
            changeOrigin: true,
            pathRewrite: {'^/api1': ''} //以api前缀开头,替换为''空串
        })
    )
}

此时,App.js中,请求的路径要加上/api1前缀,从http://localhost:3000/students变成http://localhost:3000/api1/students

import './App.css';

import React, { Component } from 'react'
import axios from 'axios';

export default class App extends Component {

  getStudent = ()=>{
    axios.get('http://localhost:3000/api1/students').then(
      response=>{
        console.log('请求成功', response.data)
      },
      err=>{
        console.log('请求失败:', err)
      }
    )
  }
  
  render() {
    return <button onClick={this.getStudent}>点我获取学生信息</button>
  }
}


server.js如下:

const express = require('express')
const app = express()

app.use((request, response, next)=>{
    console.log('有人请求服务器了');
    next()
})

app.get('/students', (request, response)=>{
    const students = [
        {id:'001', name:'tom', age:18},
        {id:'002', name:'jerry', age:19},
        {id:'003', name:'tony', age:20}
    ]
    response.send(students)
})

app.listen(5000, (err)=>{
    if(!err) console.log('服务器启动成功了,请求学生信息地址为:http:localhost:5000/students')
})

点击按钮,控制台输出信息:

二、直接在package.json中配置proxy

直接在最后面加上"proxy": "http://localhost:5000"即可

posted @ 2021-05-09 16:19  pangqianjin  阅读(467)  评论(0编辑  收藏  举报