gpt4 book ai didi

javascript - 如何修复 Nginx、Express 和 NodeJS 中的 'Cannot POST/index.html'

转载 作者:行者123 更新时间:2023-12-02 23:42:37 28 4
gpt4 key购买 nike

我正在我的生产服务器上设置我的 MERN 项目,同时确保您可以手动输入 URL(例如 myproject.com/dashboard) 我将以下行添加到我的 Nginx 配置文件 try_files $ 的 server 部分uri/index.html; 允许这样做(如react-router训练page所述)。现在,当尝试登录Cannot POST/index.html时,这会导致以下响应。

如果我删除该行,则所有对 api 的调用都可以工作(我可以再次登录),但我无法手动输入 url。

我尝试将 try_files 行移至 server 部分的顶部,以防服务器部分对此敏感。

server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name myproject.com;
root /home/forge/myproject.com/client/build;
...
location / {
try_files $uri /index.html;
proxy_pass http://127.0.0.1:8080;
}
...
}
const express = require('express');

const app = express();

app.use( express.static( `${__dirname}/client/build` ) );

app.use('/api/users', usersRouter);
app.use('/api/playlists', playlistRouter);


app.get('*', (req, res) => {
res.sendFile(`${__dirname}/client/build/index.html`);
});

我希望能够登录(调用我的 api)并手动输入 URL 到我的项目。

最佳答案

我认为您的配置无效。在您的配置中,如果请求的文件不存在,则无论如何您都会发送文件 index.html 。永远不会调用代理。

由于您的服务器具有 /api 前缀,因此请在 nginx 服务器上进行配置。因此以 /api 开头的请求将代理到您的后端服务器。

server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name myproject.com;
root /home/forge/myproject.com/client/build;

location /api/ {
proxy_pass http://127.0.0.1:8080;
}

location / {
try_files $uri /index.html;
}

}

关于javascript - 如何修复 Nginx、Express 和 NodeJS 中的 'Cannot POST/index.html',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56003656/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com