简体   繁体   中英

Node static js file isn't refreshing

I'm trying to build my first node app and am having problems with the javascript file, but not my css so I'm very confused. Here is my app.js:

var express = require("express");
var app = express();
app.set("view engine", "ejs");
app.use(express.static(__dirname + '/public'));

I couldn't load my js file until I added line 4, where I saw in the chrome console "connected", which was from my js file. The problem that I am having is that since I added line 4, express.static my js file hasn't changed and everything that I have added in the file is not showing in the chrome resources tab. Strangely though, my css file is working correctly, so I'm a little bit stumped.

I am trying linking to the js file like:

<script src="javascripts/main.js"></script>

I'm not really sure why its not working properly, I tried restarting the server and have since installed nodemon which hasn't worked either. my folder structure is

app.js
public
    stylesheets
        main.css
    javascripts
        main.js

I have looked up the problem and have only found people not connecting to static files, not once connected they aren't showing any saved changes

I think you must disable cache in your browser. Because browser think that file is not to old to be refresh from server and use cached file.
For Chrome - open console by F12 (also in other browser works) and check it.

在此处输入图片说明

Try using an absolute path to ensure static assets get loaded properly. Using relative paths (eg javascripts/main.js ) can be problematic because of the way the browser converts them to absolute paths (it takes into account the full url, including any nested routes).

So for example if you have a route /foo/bar set up and you are using relative paths, when you visit /foo/bar in your browser, the browser will try to access /foo/bar/javascripts/main.js .

The problem you are facing is already answered by the library like webpack. It does hot reloading. Whatever the changes you make to your web app, will be loaded into client and the files will be patched to update the changes without having to restart the server. You will have updated scripts running in the browser.

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