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;
to allow this(as stated by the react-router training page ). This has now caused the following response when trying to login 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.
I've tried moving the try_files
line to the top of the server
section incase the server section is sensitive to this.
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.
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. Will never call proxy.
Since your server has /api
prefix configure that on your nginx server like this. So request starts with /api
will be proxy to your backend server.
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;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.