针对跨域问题---客户端拦截github返回的数据解决方案

方案一:

  • 启动一个服务器,如果服务器的url为:http://localhost:5002,我们要获取服务器的students的信息
  • 此时脚手架的localhost地址为http://localhost:3000
  • 现在请求出现问题,客户端的3000端口可以向服务器的5002端口发送请求,但是数据返回时被3000端口拦截
  • 此时需要在package.json的最后加上服务器代理
  • “proxy”:http://localhost:5002
  • 其次在axios上的get请求服务器地址改为http://localhost:3000/students
  • 这种情况下,先找3000端口内的内容,找不到再去5002端口内找
  • 这种情况限制一种端口代理,不可再配置其他的端口代理

测试代码如下:

import React from 'react'
import axios from 'axios'
import './App.css';

export default class App extends React.Component {
  getStudentsDate = () => {
    axios.get('http://localhost:3000/students').then(
      res => { console.log('成功', res.data) }
    )

  }
  render() {
    return (
      <div>
        <button onClick={this.getStudentsDate}>点击获取学生信息</button>
      </div>
    )
  }
}

模拟服务器下:

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

app.use((request, response, next) => {
    console.log('有人请求服务器1了');
    // console.log('请求来自于',request.get('Host'));
    // console.log('请求的地址',request.url);
    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: 120 },
    ]
    response.send(students)
})

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

服务器代理配置如下在package.json文件中配置如下

{
  "name": "myapp",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.1.1",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^0.27.2",
    "node": "^17.7.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:5002"
}

方案二:

添加一个配置文件命名必须为setupProxy.js(因为脚手架会自动读取这个名字的文件)
配置内容如下:
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function (app) {
    app.use(
        createProxyMiddleware('/api1', {  //api1是需要转发的请求(所有带有/api1前缀的请求都会转发给5002)
            target: 'http://localhost:5002', //配置转发目标地址(能返回数据的服务器地址)
            changeOrigin: true, //控制服务器接收到的请求头中host字段的值
            pathRewrite: { '^/api1': '' } //去除请求前缀,保证交给后台服务器的是正常请求地址(必须配置)
        }),
        createProxyMiddleware('/api2', {
            target: 'http://localhost:5001',
            changeOrigin: true,
            pathRewrite: { '^/api2': '' }
        })
    )
}

测试文件

import React from 'react'
import axios from 'axios'
import './App.css';

export default class App extends React.Component {
  getStudentsDate = () => {
    axios.get('http://localhost:3000/api1/students').then(
      res => { console.log('成功', res.data) }
    )
  }
  getCarsDate = () => {
    axios.get('http://localhost:3000/api2/cars').then(
      res => { console.log('成功', res.data) }
    )
  }
  render() {
    return (
      <div>
        <button onClick={this.getStudentsDate}>点击获取学生信息</button>
        <button onClick={this.getCarsDate}>点击获取汽车信息</button>
      </div>
    )
  }
}

服务器内容如下

服务器1:

const express = require('express')
const app = express()
app.use((request, response, next) => {
    console.log('有人请求服务器1了');
    // console.log('请求来自于',request.get('Host'));
    // console.log('请求的地址',request.url);
    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: 120 },
    ]
    response.send(students)
})
app.listen(5002, (err) => {
    if (!err) console.log('服务器1启动成功了,请求学生信息地址为:http://localhost:5002/students');
})

服务器2:

const express = require('express')
const app = express()
app.use((request,response,next)=>{
    console.log('有人请求服务器2了');
    next()
})
app.get('/cars',(request,response)=>{
    const cars = [
        {id:'001',name:'奔驰',price:199},
        {id:'002',name:'马自达',price:109},
        {id:'003',name:'捷达',price:120},
    ]
    response.send(cars)
})
app.listen(5001,(err)=>{
    if(!err) console.log('服务器2启动成功了,请求汽车信息地址为:http://localhost:5001/cars');
})

 

这种情况下,可以随意配置多个代理,没有个数限制

 

posted @ 2022-05-02 21:16  终究还是避免不了遗憾  阅读(164)  评论(0)    收藏  举报