简体   繁体   中英

JS and Image directories loading in localhost but not when deployed express

I am using nginx as web server with cloudflare as ddns.

The JS and image directory seems to load up just fine localhost:5000/ . However, the directors are missing when I view it on aarth.in . There are many solution on such but none of them worked for me. Any help would be appreciated!

My directory is as follow

- node_modules
- server.js
- public
    - index.html
    - images/
        - base.png
        - sub
    - scripts
        - base.js
        - sub
    - css
        - base.css
        - sub/
            - sub.css

server.js

const express = require('express');
const app = express();
app.use(express.static("public"));

app.get((req, res) => {
});

app.listen(5000, () => console.log('http://localhost:5000/'));

404 errors I see in browser console.

JS 的 404 错误

For anyone facing the same issue, it turns out there was no error in server.js . I had to change the nginx default config and comment out the root.

Here is my config:

server {
        listen 80 default_server;
        listen [::]:80 default_server;                                                                                                        

        #root /var/www/html; --> Commenting this did the trick!

        server_name example.com www.example.com;

        location / {
                proxy_pass http://localhost:YOUR_PORT;
                try_files $uri $uri/ =404;
        }

        #Nginx handles all the static files instead of node
        location ~^\/(images|css|fonts|js|icons|scss) {
           expires 1M;
           access_log off;
           add_header Cache-Control "public";
           add_header Access-Control-Allow-Origin *;
           add_header Access-Control-Allow-Methods GET;
           add_header Access-Control-Allow-Headers X-Requested-With,content-type;
           add_header Access-Control-Allow-Credentials true;
           root /home/pi/Documents/Website/public;
       }
}

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