0

This is my folder structure:

- getable_challenge
  - node_modules
    - stuff
  - main.html
  - main.js
  - backend.js
  - README.md

I want to load main.js from within main.html. Previously I had been accessing the page using the URL of file:///Users/adamzerner/code/getable_challenge/main.html, and a simple <script src="main.js"></script> allowed me to load the script.

But then I set up a Node server, at localhost:3000, and now it won't load the script. It's trying to load localhost:3000/main.js, which presumably is the wrong path. I'm not sure how to structure this... what should I do?

Server code (essentially)

var express = require('express');
var app = express();
app.listen(3000);
2
  • Post your server code. Did you setup the server to know where you static resources are? Commented Jan 19, 2015 at 18:16
  • @ShanRobertson posted. No, I didn't know that, how or why to do that. Commented Jan 19, 2015 at 18:18

2 Answers 2

1

When you use the "file" protocol like that you aren't even using the web app to serve the script, you are directly accessing it on the local file system. That works fine when you are just running your app on your local machine but it completely breaks when you try to run it as a real app since the browser will have no idea where "file:///..." is, or even have permission to access it.

You need to put the client side scripts into a separate directory, usually named 'public', and then make your application aware of it. If you're using express you would do this:

app.use(express.static(__dirname + '/public'));

You want to put your statically served scripts ("public") into a separate directory so as to control access by your clients. If you just put them into the main directory and made the main directory accessible you could expose all your other files to public view, such as config files that sometimes contain passwords.

It also makes your structure much cleaner.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah ok, thanks! Why does it have to be in a separate directory?
0

Try adding this line after var app

app.use(express.static(__dirname));

This should make your resources that are within your servers folder accessible. the var __dirname is the path to where your server is executed.

3 Comments

While suggesting express.static is the right idea, using __dirname as root path is a bad idea.
Your comment serves no purpose without a reason as to why. Please educate us!
Sure. Using __dirname will make all files in this directory accessable to public, which is at least the file you have the app.use(...) in. As of that you might expose some vulnerable informations.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.