繁体   English   中英

如何在Nginx,Express和NodeJS中修复'Cannot POST /index.html'

[英]How to fix 'Cannot POST /index.html' in Nginx, Express and NodeJS

我在生产服务器上设置我的MERN项目,同时确保您可以手动键入URL(例如myproject.com/dashboard ),我在Nginx配置文件try_files $uri /index.html;server部分中添加了以下行try_files $uri /index.html; 允许这样做(如react-router培训页面所述 )。 现在,当尝试登录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;
  }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM