[英]How to fix 'Cannot POST /index.html' in Nginx, Express and NodeJS
I'm setting up my MERN project on my production server and whilst making sure you can manually type in URL (such as myproject.com/dashboard
) I added the following line to the server
section of my Nginx configuration file try_files $uri /index.html;
我在生产服务器上设置我的MERN项目,同时确保您可以手动键入URL(例如myproject.com/dashboard
),我在Nginx配置文件try_files $uri /index.html;
的server
部分中添加了以下行try_files $uri /index.html;
to allow this(as stated by the react-router training page ). 允许这样做(如react-router培训页面所述 )。 This has now caused the following response when trying to login Cannot POST /index.html
. 现在,当尝试登录Cannot POST /index.html
时,导致以下响应。
If I remove the line all calls to the api work(i can login again) but I cannot enter url manually. 如果我删除该行,则所有对api工作的调用(我可以再次登录),但无法手动输入url。
I've tried moving the try_files
line to the top of the server
section incase the server section is sensitive to this. 我尝试将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`);
});
I expect to be able to login(make calls to my api) and enter URLs manually to my project. 我希望能够登录(调用我的api)并手动输入URL到我的项目。
I think your configuration is not valid. 我认为您的配置无效。 In your config if requested file does not exists you are sending the file index.html
no matter what. 在配置中,如果所请求的文件不存在,则无论如何都将发送文件index.html
。 Will never call proxy. 永远不会调用代理。
Since your server has /api
prefix configure that on your nginx server like this. 由于您的服务器具有/api
前缀,因此请在nginx服务器上进行配置。 So request starts with /api
will be proxy to your backend server. 因此,以/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.