简体   繁体   中英

Why do I not need to reference the relative path in my html file to load a javascript file with express js?

I'm building my first project from scratch and as I'm setting it up I noticed that, using the relative path to my javascript file failed from my index.html file, but referencing it just by its name worked?

  1. Attached directory structure. As you can see index.ejs is in src/views while my script is in src/jscript . This means my path should be ../jscript/index.js from my index.ejs file.

在此处输入图片说明

  1. Express JS file code

     const express = require('express') const app = express() const port = 9900 app.use(express.static('src/img')) app.use(express.static('src/css')) app.use(express.static('src/jscript')) app.use(express.static('src/fonts')) app.set('views', 'src/views'); app.set('view engine', 'ejs'); app.get('/', (req, res) =>{ res.render('index') });
  2. HTML that works

<script type="text/javascript" src="index.js"></script>

So to recap, my question is why does the above html script referencing the js file without the correct path work. I know it's probably the app.use static file that points to a directory but I just want to double check why that is. Thanks!

Relative URLs are resolved by the browser not the server.

The browser isn't requesting /views/index.ejs it is requesting / .


You also said app.use(express.static('src/jscript')) so the URL to index.js is /index.js .


/ (URL of the HTML) + index.js (relative URL to the JS) = /index.js (URL of the JS).

it's probably the app.use static file that points to a directory

This is the exact right answer. Plus I suggest to refactor this app.use in a single liner:

app.use(express.static('src'));

And change the references accordingly in the views.

Please notice that usually the architecture has an src folder that compiles to a public one so you would place the public folder in the express.static declaration.

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