Monday, 15 April 2013

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


My Express app works on an HTML page from My Disk on the initial GET (i.e., if I can hit "" in the browser).

  & lt; Script src = "/ myJavaScriptFile.js" type = "text / javascript" & gt; & Lt; / Script & gt; And try to include it in 'index.html'.  

or

  & lt; Script src = "./ myJavaScriptFile.js" type = "text / javascript" & gt; & Lt; / Script & gt;  

or

  & lt; Script src = "~ / MyAbsolutePath / myJavaScriptFile.js" type = "text / javascript" & lt; / Script & gt;  

This does not work MyJavaScriptFile.js file never reached.

My Express App looks like this:

  var express = require ('express') var testMethod = ('./ test') var app = Express (): App.use (bodyParser.urlencoded ({extended: incorrect})); Var server = app.listen (3000, function () {var host = server.address (). Address var port = server.address (). Port console.log ('http: //% listening on example' A: % S ', host, port)}) app.get (' / ', function (req, res) {console.log (' in / '); res.sendFile (__dirname +' /index.html ');} )  

Express App Reference Path '__dirname' + '/index.html' is serving 'index.html' using the res.sendFile function. (I think this is a bad way of doing this. Please tell me if you think so).

Also, as we can see in the Express Apache, an external javascript file that is 'exam', which includes 'index.html' and 'express.js' without any issue going. Can anyone shed light on what's really happening in the background? What exactly will the context in the context of the javascript file that I can give in my 'index.html' if it is served by the Express app? Thank you.

Files, such as images, CSS, JavaScript and other static files Express-Express.Textic includes a built-in middleware Help of

Pass the name of the directory, which is to be marked as the location of static assets, which is to start the service from the Express.Testatic Middleware. For example, if you have your images, If you put CSS and Javascript files in a public named directory, you can:

  the app. (Express 'static' 'public');  

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

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

Happy help!


No comments:

Post a Comment