javascript NGINX反向代理不代理Express应用程序

jei2mxaa  于 2023-08-02  发布在  Java
关注(0)|答案(3)|浏览(119)

我试图为一个在/mypath上服务的网站设置一个单独的API后端,但NGINX似乎并没有真正代理请求。
sites-enabled nginx配置:

upstream backend_website {
        server 127.0.0.1:5173;
}

upstream backend_api {
        server 127.0.0.1:5001;
}

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

       server_name example.com;

       # Redirect to HTTPS (:443)
       return 301 https://$host$request_uri;
}

# HTTPS
#
server {
        listen 443 ssl;
        listen [::]:443 ssl;

        ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

        server_name example.com;

        location / {
                include proxy_params;
                proxy_pass https://backend_website;
        }

        location /mypath {
                include proxy_params;
                proxy_pass https://backend_api;
        }
}

字符串
服务的index.ts文件

import cors from "cors";
import express from "express";
import { config } from "config";
import { MyController } from "controllers/my.controller";
import * as https from "https";
import * as fs from "fs";

const certificate = fs.readFileSync("/etc/letsencrypt/live/example.com/fullchain.pem", "utf8");
const privateKey = fs.readFileSync("/etc/letsencrypt/live/example.com/privkey.pem", "utf8");

const app = express();
app.use(express.json());
app.use(cors());
app.use("/", MyController );

const httpsServer = https.createServer({
    cert: certificate,
    key: privateKey
}, app);

httpsServer.listen(config.PORT, "127.0.0.1", () => console.log(`Running api on https://127.0.0.1:${ config.PORT }/`));


但是,服务器不会将请求代理到API。它在根路径上完美地工作(使用Vite),但是当打开我刚刚得到的URL时,/mypath不起作用。我使用lynx打开了127.0.0.1:5001,它确实工作。所以问题就出在NGINX的某个地方。

nkkqxpd9

nkkqxpd91#

您需要编辑/etc/nginx/site-enabled/文件

cd /etc/nginx/site-enabled/
 sudo nano default

个字符
然后在这个图片的帮助下在位置功能中编辑。rfr image

gmxoilav

gmxoilav2#

把你的nginx配置改成这样。

location  /mypath {
      rewrite /foo/(.*) /$1  break;
      proxy_pass         https://backend_api;
      proxy_set_header   Host $host;
}

字符串
然后尝试调用http://example.com/mypath/

xwbd5t1u

xwbd5t1u3#

我找到了答案。出于一些不直观的原因,您必须指定Express应该在/mypath/上服务,即使您已经在NGINX配置文件中告诉过。
所以这个代码

const app = express();
app.use(express.json());
app.use(cors());
app.use("/", MyController );

const httpsServer = https.createServer({
    cert: certificate,
    key: privateKey
}, app);

httpsServer.listen(config.PORT, "127.0.0.1", () => console.log(`Running api on https://127.0.0.1:${ config.PORT }/`));

字符串
变成了那样

const app = express();
app.use(express.json());
app.use(cors());
app.use("/mypath", MyController );

const httpsServer = https.createServer({
    cert: certificate,
    key: privateKey
}, app);

httpsServer.listen(config.PORT, "127.0.0.1", () => console.log(`Running api on https://127.0.0.1:${ config.PORT }/`));

相关问题