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


my express app serves html page disk upon initial (i.e., if hit "http://localhost:3000/" in browser). access javascript file in same location in disk html file. when try include in 'index.html' 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. myjavascriptfile.js file never reached.

my express app looks 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 @ http://%s:%s', host, port)   })   app.get('/', function (req, res) {  console.log('in /');  res.sendfile(__dirname + '/index.html');  }) 

express app serving 'index.html' using reference path '__dirname' + '/index.html' using res.sendfile function. (i beginning feel bad way of doing it. please let me know if think too).

also can see in express app, external javascript file called 'test' in same location 'index.html' , 'express.js' being included without issues. please shed light on what's happening in background? reference path javascript file can give in 'index.html' if being served express app? thank you.

serving files, such images, css, javascript , other static files accomplished of built-in middleware in express - express.static.

pass name of directory, marked location of static assets, express.static middleware start serving files directly. example, if keep images, css, , javascript files in directory named public, can this:

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

now, able load files under 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!


Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

[C++][SFML 2.2] Strange Performance Issues - Moving Mouse Lowers CPU Usage -

ios - Possible to get UIButton sizeThatFits to work? -