【问题标题】:How to fix 'Cannot POST /index.html' in Nginx, Express and NodeJS如何在 Nginx、Express 和 NodeJS 中修复“无法发布 /index.html”
【发布时间】:2019-09-23 23:57:33
【问题描述】:

我正在我的生产服务器上设置我的 MERN 项目,同时 确保您可以手动输入 URL(例如 myproject.com/dashboard)我将以下行添加到我的 Nginx 配置文件 try_files $uri /index.html;server 部分以允许这样做(如 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。

【问题讨论】:

    标签: javascript node.js express nginx react-router


    【解决方案1】:

    我认为您的配置无效。在您的配置中,如果请求的文件不存在,则无论如何您都将发送文件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;
      }
    
    }
    

    【讨论】:

    • 这行得通,谢谢。你的解释很有道理!
    猜你喜欢
    • 2013-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多