简体   繁体   中英

Loading scripts in a Node app

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);

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.

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.

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