簡體   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