1

My express app serves an HTML page from my disk upon the initial GET (i.e., 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.

1 Answer 1

4

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!

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

Comments

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.