React 小知识 - 跨域代理

314 阅读2分钟

喜欢直接上代码,两个后端服务,一个搜索组件。node 起一个小服务还是很快的,不像 java 那么繁重

// server1.js 服务一
const express = require("express");
const app = express();

const data = [{
		id: 1,
		name: "zhangsan",
		age: 25
	},
	{
		id: 2,
		name: "lisi",
		age: 18
	}
]

app.get("/person", (request, response) => {
	console.log(request.get("Host")); // 这里的打印暂时不用管,下文会提到 !!!
	response.send(data);
});

app.listen(5000);
console.log("服务已经启动,地址:http://localhost:5000");
// server2.js 服务二
const express = require("express");
const app = express();

const data = [{
		id: 1,
		name: "特斯拉",
		price:"2.8w"
	},
	{
		id: 2,
		name: "奔驰",
		age: "1.6w"
	}
]

app.get("/car", (request, response) => {
	response.send(data);
});

app.listen(5001);
console.log("服务已经启动,地址:http://localhost:5001");

搜索组件 图

image.png

// 搜索组件
// 使用了 bootstrap
import React, { Component } from 'react'
import axios from "axios" // yarn add axios   安装 axios库,用于发起 XMLHttpRequest 请求

export default class index extends Component {

    handleSearch = () => {
        const requestPath = "http://localhost:5000/person";
        axios.get(requestPath).then(res => {
            console.log(res.data);
        })
    }

    render() {
        return (
            <div className="search">
                <input className="form-control" type="text" placeholder="请输入需要搜索的关键字" />
                <button className="btn btn-info" onClick={this.handleSearch}>搜索</button>
            </div>
        )
    }
}


由于我们还未配置代理,所以直接点击搜索按钮会出现跨域,如图

image.png

所以第一种配置代理方式,直接找到 package.json 文件,在最后一个大括号前面配置,记得加个逗号

,"proxy":"http://localhost:5000"

不过,与之对应的,我们需要在搜索组件修改请求路径。重新 npm start ,点击搜索按钮

const requestPath = "http://localhost:3000/person"; // 会优先从3000端口找目标,如果不存在则会去5000端口找目标

image.png

想必到这一步,应该已经成功了。但是涉及到多个请求地址,那就需要多个代理
在 src 目录下新建 setupProxy.js(不要问我为什么叫这个名字)

// setupProxy.js
// 如果运行提示 http-proxy-middleware 有问题,那就 yarn add http-proxy-middleware 
// 不过要保证 node 版本大于 12.x.x (亲测)
const {createProxyMiddleware} = require("http-proxy-middleware")

module.exports = function(app){
    app.use(createProxyMiddleware("/api1",{
        target:"http://localhost:5000", // 访问的目标地址
        changeOrigin:false, // Host 信息,默认 false 建议改为 true !!! 就是这里,在 server1.js 有个console 信息,观察 true or false 的打印不同信息
        pathRewrite:{ // 路径重写,将 /pai1 替换为 空字符串 -> http://localhost:5000/person
            "^/api1":""
        }
    }));

    app.use(createProxyMiddleware("/api2",{
        target:"http://localhost:5001",
        changeOrigin:true,
        pathRewrite:{
            "^/api2":""
        }
    }));
    
}

采用第二种代理方式之前,记得删除 package.js 的 proxy 属性
配置完 setupProxy.js 之后,还是需要修改搜索组件的请求路径,重新 npm start

const requestPath = "http://localhost:3000/api2/car";

直接看请求成功图,可以试试 http://localhost:3000/api1/person 也是成功的

image.png

有不懂的,希望不要问我,我也是看教学视频学的,总结自己学到的东西
结束,再见!