简体   繁体   中英

ExpressJS always serving the index

So I have a problem with my react SPA. I created it using create-react-app and all the built files (including the index.html, all js, css and images) are collected in the build folder.

The server is set up in two parts.

First is the nginx webserver.

server {
    listen 443 ssl ;

    server_name beta.frpgame.ru;
    ssl_certificate /etc/letsencrypt/live/frpgame.ru/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/frpgame.ru/privkey.pem;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';

    access_log /home/malkav/demiurge/client/logs/access.log;
    error_log  /home/malkav/demiurge/client/logs/error.log;

    location / {
        proxy_pass http://localhost:5000;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
    }
}

server {
    listen 80;
    server_name beta.frpgame.ru;
    rewrite ^/(.*) https://beta.frpgame.ru/$1 permanent;
}

Second is the ExpressJS server that the nginx server proxies to.

const express = require('express');
const path = require('path');
const compression = require('compression');
const port = process.env.NODE_PORT || 5000;
const app = express();

app.use(compression());
app.use(express.static(path.join(__dirname, 'build')));

app.get('/*', function (req, res) {
    res.sendFile(path.join(__dirname, 'build', 'index.html'));
});

app.listen(port);
console.log('App is listening on port ' + port);

When you load the website in your browser (the host name is listed), it looks pretty normal, images and scripts work as expected. But on the first load and after a new deploy it may take 2 or 3 tries. I believe it's because the static files on the server are for some reason not accessible via direct link. If you try to load an image or css/js file, you'll get the index.html .

I have already tried mocking with the line order in the server.js but with little to no result. Changing to app.get('/' ... doesn't change anything either.

I ended up switching to pure NGINX setup and removed the node server alltogether. I'll need to get it back once I get to SSR, but that'll be another story.

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.

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