My npm http-server problem

I think I have properly installed npm http-server. My problem has to do with accessing folders at a higher level in the directory than where index.html is located. The basic file structure is this:
./libs/three/three.js
./css/default.css
./src/subdir/js/app.js
./src/subdir/index.html

In index.html, external JS files are referenced at:
…/…/libs/three/three.js
…/…/css/default.css

My startup sequence (Windows 10) looks like this:
In command prompt (created when NPM installed)
Navigate to folder containing index.html
Start http-server
In browser (Chrome) enter URL:
http://localhost:8080/index.html

The html “title” is reproduced in the browser tab but all the files in folders higher in the file system than index.html are not found (“Error 404”). For example, yields an error.

If I move the “not found” files down to the index.html level all is fine.
What’s wrong?

Your node server will only serve files below the level that it is run in for security reasons. So you will need to run your server in the ./ directory, and access the page using http://localhost:8080/src/subdir/index.html

If the node server didn’t work this way, running a server would allow external people access to all the files on your computer, which I’m sure nobody wants.

2 Likes

Thanks, calrk, for the clear explanation. It makes perfect sense. The “not found” error (404) isn’t very helpful but how would the html processor know to tell the user the whole story?

The main problem is what @calrk mentioned, if you are looking for ways to setup your project you can read further.

By convention the files you want to make public from your server is put in a public folder.
You ideally only want to expose that to the public internet and and you can put all your html, js, css files there.

Then you could start your server from the public folder and in your html the path / will refer to this folder and you can point to files below it from there. eg:
/js/libs/three.js,
/css/style.css etc.

src folders are best not exposed and if you have code in there you want to expose to public you ideally run an automated process to ‘build’ it into the public folder (which could just mean copying it).

Thanks amitizkpa for your input to my beginner problem with running http-server.

I am working strictly locally on my own computer building “fun” projects. (You know software engineering: 90% sweat and frustration, 10% “hurray, it works”.) But I might build a Web app or two on a publicly accessible site available through my ISP. So your input is very much appreciated.