通过反向代理为基于两个节点服务器的前端提供服务时出错

问题描述 投票:0回答:1

我只有一个域,因此需要通过nginx反向代理服务在两个不同的节点服务器上运行的两个不同的React应用程序。这是我的nginx.conf文件

server {
  listen 80;
  listen [::]:80;

  client_max_body_size 128g; # allows larger files (like videos) to be uploaded.

  location / {
      proxy_pass http://192.168.0.105:8081;
  }

  location /admin {
      proxy_pass http://192.168.0.105:8080;
  }

}

[我想在这里实现的是,如果用户登陆abc.com,那么将为他提供来自http://192.168.0.105:8081的应用程序的响应,而如果用户访问abc.com/admin,则将为他提供http://192.168.0.105:8080的]。>

两个应用程序都有不同的节点服务器,它们服务于由create-react-app创建的react束。两个应用程序的节点的server.js都看起来像这样

const express = require("express");
const bodyParser = require("body-parser");
const path = require("path");
const cors = require("cors");
const app = express();
const qs = require("querystring");

const axios = require("axios");

const PORT = process.env.PORT || 8080;

const serverEnvironment = process.env.serverEnv || "dev";

app.use(cors());
app.use(express.static(path.join(__dirname, "build")));

app.use(bodyParser.json());

app.get("*", function(req, res) {
  console.log("Requesting Admin Portal");
  res.sendFile(path.join(__dirname, "build", "index.html"));
});

app.listen(PORT, () => {
  console.log(
    `\nPortal is being served in ${serverEnvironment} environment at port ${PORT}`
  );
  console.log(
    "\x1b[33m%s\x1b[0m",
    "\nThe environment logged above is the environment of node server which is " +
      "\ndifferent from your react app's environment. That should be passed during the build of react application as REACT_APP_ENV\n"
  );
});

当我访问本地主机时一切正常:4000(4000是运行nginx的端口),它可以为我提供预期的门户。但是,当我访问localhost:4000 / admin而不是提供管理应用程序时,最终会出现以下错误

Uncaught SyntaxError: Unexpected token '<' 2.0f3deea8.chunk.js:1 
Uncaught SyntaxError: Unexpected token '<' main.a2e30dbb.chunk.js:1

当我检查“网络”选项卡时,所有的js和css块都返回HTML,而不是相关的js或css。

我也尝试添加

location ~ .(static)/(js|css|media)/(.+)$ {
        try_files $uri $uri/ /$1/$2/$3;
    }

到nginx.conf,但没有用。我在这里遗漏了什么吗,还是不是反向代理2应用程序的正确方法?

我只有一个域,因此需要通过nginx反向代理服务在两个不同的节点服务器上运行的两个不同的React应用程序。这是我的nginx.conf文件服务器{听80;听[...

node.js reactjs nginx create-react-app nginx-reverse-proxy
1个回答
0
投票

您是否在网络标签中看到js / css的index.html内容?如果是,则通常是由于index.html中的基本href错误造成的。

© www.soinside.com 2019 - 2024. All rights reserved.