繁体   English   中英

http-proxy 模块不适用于 create-react-app,但适用于 serve -s build

[英]http-proxy module doesn't work with create-react-app, but works with serve -s build

http-proxy模块不适用于create-react-app ,但适用于serve -s build

这是我的代理服务器代码。

那么它做了什么 - 它将不同端口上的 2 个 api 服务器和前端连接到一个 80 端口。 当你打开localhost:80/*它应该打开反应前端(3000 端口)。 当您打开/api时,它会为您提供来自 4000 端口的数据和来自 1000 端口的/secondapi

我的 2 个后端 api 服务器完全可以正常打开。

此外,当我使用serve模块启动前端服务器时,它也可以正常工作并返回我的前端部分。

但是,如果我使用“npm start”在同一个 3000 端口启动前端,我的代理服务器将返回connect ECONNREFUSED::1:3000

const httpProxy = require('http-proxy');
const http = require('http');
const { maintenanceHtml } = require('./maintenanceHtml');


const proxy = httpProxy.createServer();

const guiUrl = 'http://localhost:3000'; // react frontend app

const apiUrl = 'http://localhost:4000'; // 1st api server
const apiPrefix = '/api';

const fnApiUrl = 'http://localhost:1000'; // 2nd api server
const fnApiPrefix = '/secondapi';

const port = 80;

http.createServer((req, res) => {
  let target = guiUrl;
  if (req.url.startsWith(apiPrefix)) {
    req.url = req.url.replace(apiPrefix, '/');
    target = apiUrl;
  }
  if (req.url.startsWith(fnApiPrefix)) {
    req.url = req.url.replace(fnApiPrefix, '/');
    target = fnApiUrl;
  }
    proxy.web(req, res, { target })

    proxy.on('error', (error) => {
      console.log(error.message)
      res.end(maintenanceHtml);
    })
}).listen(port, () => {
  console.log(`Proxy server has started on port 80`)
});

我认为有一些我找不到的反应服务器设置。

有一个小例子,您可以从自己的 PC 开始。

https://github.com/b2b-Alexander/react-js-问题

在github上找到解决办法: https://github.com/vitejs/vite/discussions/7620

我安装了新的 v18.12.1 版本的 NodeJS。

我的主机有 v16.14.0

所以我为我的项目回滚了 NodeJS 的版本。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM