V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Gav1nw
V2EX  ›  程序员

React 下的 http-proxy-middleware 转发错误

  •  
  •   Gav1nw · 2023-03-15 16:50:59 +08:00 · 848 次点击
    这是一个创建于 379 天前的主题,其中的信息可能已经有所发展或是发生改变。

    最近写了一个前后端分离的框架,因为涉及到多个 API 的调用,存在跨域的问题,所以使用了 http-proxy-middleware (以下称为 HPM )

    版本:

    1. React 18.2.0
    2. HPM 版本 2.0.6 npm 最新版本 使用 Typescript

    目标: "/map_services/v1/getVersion" -> "http://localhost:8810/v1/getVersion"

    问题: 1. /map_services 确实被代理了,但后端服务器显示请求的是"http://localhost:8810/map_services/v1/getVersion" 即 PathRewrite 并没有生效 2. 我发起的是 POST 请求,但后端服务器显示收到的是 GET 请求

    后端请求

    export const getVersion = async (): Promise<string> => {
        return await http("/map_services/v1/getVersion", {
            method: HTTP_METHODS.POST,
            data: {}
        }).then((response) => {
            if (response.data !== "") {
                return response.data;
            }
            return "null";
        })
    }
    const http = async (url: string,
        {data, headers, ...customConfig}: IConfig = {})=>{
     数据处理就不写了
     ···
    
     return await window.fetch(url, config).then(async (res) => {
            let dataRes: IRemoteResponse = await res.json();
            if (dataRes.info !== SUCCESS_FLAG) {
                return Promise.reject({message: "Bad Request!"});
            }
            if (dataRes.info) {
                return dataRes;
            } else {
                return Promise.reject(dataRes);
            }
        });
    
    }
    

    setupProxy.js

    
    const {createProxyMiddleware} = require('http-proxy-middleware');
    module.exports = function (app) {
    app.use(
            '/map_services',
            createProxyMiddleware({
                target: 'http://localhost:8810',
                PathRewrite: {
                    '^/map_services': '/'
                }
            })
        );
    }
    
    4 条回复    2023-03-16 21:46:56 +08:00
    abelyao
        1
    abelyao  
       2023-03-15 17:01:19 +08:00
    试试 target: 'http://localhost:8810/'
    以 / 结尾,然后去掉 PathRewrite
    wzdsfl
        2
    wzdsfl  
       2023-03-15 17:03:37 +08:00
    我在项目里是这么设置的
    ```
    '/api/example': {
    target: 'http://example.com',
    changeOrigin: true,
    rewrite: (path) => path.replace(/^\/api\/example/, '')
    },
    ```
    7anshuai
        3
    7anshuai  
       2023-03-15 18:42:35 +08:00   ❤️ 1
    PathRewrite -> pathRewrite ,大小写问题?
    Gav1nw
        4
    Gav1nw  
    OP
       2023-03-16 21:46:56 +08:00
    看了一下真的是!!!太感谢了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5368 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 07:29 · PVG 15:29 · LAX 00:29 · JFK 03:29
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.