简体   繁体   中英

How do I include an external JavaScript file when serving an HTML file with a response object in expressjs?

My express app serves an HTML page from my disk upon the initial GET (ie, if I hit " http://localhost:3000/ " in the browser). Now I would like to access a JavaScript file which is in the same location in the disk as the HTML file. When I try to include it in 'index.html' by using

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

or

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

or

 <script src="~/MyAbsolutePath/myJavaScriptFile.js" type="text/javascript"</script>

it doesn't work. The myJavaScriptFile.js file is never reached.

My express app looks like this:

 var express = require('express')
 var testMethod = require('./test')
 var app = express()
 app.use(bodyParser.urlencoded({ extended:false }));

 var server = app.listen(3000, function () {

 var host = server.address().address
 var port = server.address().port

 console.log('Example app listening at http://%s:%s', host, port)

 })

 app.get('/', function (req, res) {
 console.log('In /');
 res.sendFile(__dirname + '/index.html');
 })

Express app is serving 'index.html' using the reference path '__dirname' + '/index.html' using res.sendFile function. (I am beginning to feel that this is a bad way of doing it. Please let me know if you think so too).

Also as we can see in the express app, an external JavaScript file called 'test' which is in the same location as 'index.html' and 'express.js' is being included without any issues. Could anyone please shed light on what's actually happening in the background? What exactly would be reference path for the JavaScript file that I can give in my 'index.html' if it is being served by express app? Thank you.

Serving files, such as images, CSS, JavaScript and other static files is accomplished with the help of a built-in middleware in Express - express.static.

Pass the name of the directory, which is to be marked as the location of static assets, to the express.static middleware to start serving the files directly. For example, if you keep your images, CSS, and JavaScript files in a directory named public, you can do this:

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

Now, you will be able to load the files under the public directory:

http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html

More Detail Here

Happy Helping!

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