【问题标题】:react app browser proxy with http-proxy-middleware使用 http-proxy-middleware 反应应用浏览器代理
【发布时间】:2020-08-28 11:35:26
【问题描述】:

我在 React 应用程序中遇到了代理问题。 目标:我有两个反应应用程序,第一个应用程序在 localhost:3000 上,第二个应用程序在 localhost:3001 上。我想要的是? => 在第一个应用程序中我会点击:

<a href="/app2">
<button>Second App Open</button>
</a>

然后 url 将从 localhost:3000 变为 localhost:3000/app2 并且第二个反应应用程序显示 url localhost:3001 中的内容。

我导入了http-proxy-middleware库并在src方向文件setupProxy.js里面创建:

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

module.exports = function(app) {
    app.use(
        createProxyMiddleware('/app2',{
            target: 'http://localhost:3001',
            changeOrigin: true,
            prependPath: false,
            secure: false,
            logLevel: 'debug',
            ws:true
        })
    );
app.listen(3000)
};

谁能帮我解决这个问题?

我也在 setupProxy.js 中尝试了这段代码:

const express = require('express')
const {createProxyMiddleware} = require("http-proxy-middleware");
app = express()
    app.use(
        createProxyMiddleware('/app2',{
            target: 'http://localhost:3001',
            changeOrigin: true,
            prependPath: false,
            secure: false,
            logLevel: 'debug',
            ws:true
        })
    );
app.listen(3000)

但后来我收到 require(...) 不是函数 oraz 表示 express 不是函数的错误,当我将 express 放入 {} 时也会发生错误。

【问题讨论】:

    标签: javascript reactjs proxy reverse-proxy http-proxy-middleware


    【解决方案1】:

    我知道已经很晚了,我遇到了同样的问题。保留对我有用的东西,以便其他人可以尝试一下。此代码已针对使用 create-react-app 创建的 react 应用程序进行了测试。

    我代理了这个端点 - https://services.odata.org/V2/Northwind/Northwind.svc/Customers?$format=json

    setupProxy.js

    const { createProxyMiddleware } = require('http-proxy-middleware');
    module.exports = (app) => {
        app.use(createProxyMiddleware('/api2', {
            target: 'https://services.odata.org/V2/Northwind/Northwind.svc/',
            changeOrigin: true,
            pathRewrite: { '^/api2': '' }
        })
        );
    }
    

    您的 .js 文件

    triggerCORSCall() {
        axios.get(`/api2/Customers?$format=json`)
          .then(response => {
            alert('Success');
          }).catch(error => {
            alert('Failure');
            console.log(error);
          })
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多