簡體   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