react脚手架配置代理

问题描述

前端发送http://localhost:5000/students请求,遇到跨域问题。
在这里插入图片描述

nodejs实现后端服务器

const express = require("express");

const app = express();

app.get("/students",(request,response) => {
    const students = [
        {id:"001",name:"张三"},
        {id:"002",name:"李四"},
        {id:"003",name:"王五"}
    ];

    response.send(students);
})

app.listen("5000",error => {
    if(!error) console.log("listening on port:5000");
})

react脚手架构建前端项目

代码涉及的主要文件有,

  1. package.json
  2. App.js

package.json

{
  "name": "react16_demo",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.2.0",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^0.27.2",
    "react": "^18.1.0",
    "react-dom": "^18.1.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

App.js

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

export default class App extends Component {
  getStudentData = () => {
    axios.get("http://localhost:5000/students").then(
      response => {
        console.log("请求成功了",response.data);
      },
      error => {
        console.log("请求失败了",error.message);
      }
    )
  }

  render() {
    const {getStudentData} = this;
    return (
      <div>
        <button onClick={getStudentData}>获取学生数据</button>
      </div>
    )
  }
}

解决办法

react脚手架配置代理可解决以上跨域问题。代理配置有以下两种方式:

  1. 第一种,package.json里添加proxy配置项,并将proxy值设置为目标服务器。如,"proxy":"http://localhost:5000"

  2. 第二种,src目录下新建代理配置文件setupProxy.js,配置内容如:

const {createProxyMiddleware} = require("http-proxy-middleware");

module.exports = function(app){
    app.use(
        createProxyMiddleware("/api",{
            target:"http://localhost:5000", 
            changeOrigin:true,
            pathRewrite:{'^/api1':''} 
        })
    )
}

配置代理服务器的第一种方法

代码变更涉及的文件有,

  1. package.json
  2. App.js

在这里插入图片描述

package.json

变更的部分是:添加proxy配置项,且proxy配置为目标服务器,即localhost:5000

{
  "name": "react16_demo",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.2.0",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^0.27.2",
    "react": "^18.1.0",
    "react-dom": "^18.1.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "proxy":"http://localhost:5000"
}

App.js

变更部分:axios.get("http://localhost:5000/students")变更为axios.get("http://localhost:3000/students")

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

export default class App extends Component {
  getStudentData = () => {
    axios.get("http://localhost:3000/students").then(
      response => {
        console.log("请求成功了",response.data);
      },
      error => {
        console.log("请求失败了",error.message);
      }
    )
  }

  render() {
    const {getStudentData} = this;
    return (
      <div>
        <button onClick={getStudentData}>获取学生数据</button>
      </div>
    )
  }
}

配置代理服务器的第二种方法

代码变更涉及的文件有,

  1. src下新增代理配置文件setupProxy.js,即src/setupProxy.js
  2. App.js

在这里插入图片描述

src/setupProxy.js

const {createProxyMiddleware} = require("http-proxy-middleware");

module.exports = function(app){
    app.use(
        createProxyMiddleware("/api",{
            target:"http://localhost:5000", 
            changeOrigin:true,
            pathRewrite:{'^/api':''} 
        })
    )
}
  • target,即目标服务器。
  • pathRewrite,即路径重写。请求路径中的字符串/api将被空字符串代替。
  • changeOrigin

App.js

变更部分:axios.get("http://localhost:5000/students")变更为axios.get("http://localhost:3000/api/students")

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

export default class App extends Component {
  getStudentData = () => {
    axios.get("http://localhost:3000/api/students").then(
      response => {
        console.log("请求成功了",response.data);
      },
      error => {
        console.log("请求失败了",error.message);
      }
    )
  }

  render() {
    const {getStudentData} = this;
    return (
      <div>
        <button onClick={getStudentData}>获取学生数据</button>
      </div>
    )
  }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值