Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs/express include local js file

Here is my current folder structure

css
   app.css
js
  app.js
node-modules
index.html
node-server.js
package.json

The node-server is hosting index.html, but I can't figure out how to get the app.js and app.css files to get loaded.

index.html loads them with:

<script src="js/app.js"></script>
<link rel="stylesheet" type="text/css" href="css/app.css"/>

Here is the error message:

Failed to load resource: the server responded with a status of 404 (Not Found)
2http://localhost:3000/css/app.css Failed to load resource: the server 
responded with a status of 404 (Not Found)

I know i need to require or load module or something, just can't figure out what.

Thanks

like image 452
NorCalKnockOut Avatar asked Mar 30 '15 22:03

NorCalKnockOut


People also ask

How do you include another js file in Node JS?

To include functions defined in another file in Node. js, we need to import the module. we will use the require keyword at the top of the file. The result of require is then stored in a variable which is used to invoke the functions using the dot notation.

How do you include a JavaScript file?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file.

Is Node JS included with JavaScript?

NodeJS is a cross-platform and opensource Javascript runtime environment that allows the javascript to be run on the server-side. Nodejs allows Javascript code to run outside the browser. Nodejs comes with a lot of modules and mostly used in web development.


1 Answers

Reason Node.Js does not server static content on it's own, routes has to defined for serving static content via Node.

Solution(Manual):

var express = require('express'),
    path = require('path'),
    app = express();

app.get('/index.html',function(req,res){
   res.sendFile(path.join(__dirname + '/index.html')); 
});

app.get('/css/app.css',function(req,res){
    res.sendFile(path.join(__dirname + '/css/app.css')); 
});

app.get('/js/app.js',function(req,res){
    res.sendFile(path.join(__dirname + '/js/app.js')); 
});

app.get('/', function(req, res) {
    res.redirect('index.html');
});

app.listen(8080);

Better Solution:

Directory Structure:

public
 css
   app.css
 js
  app.js
 index.html

CODE:

var express = require('express'),
    path = require('path'),
    app = express();

// Express Middleware for serving static files
app.use(express.static(path.join(__dirname, 'public')));

app.get('/', function(req, res) {
    res.redirect('index.html');
});

app.listen(8080);
like image 70
Nivesh Avatar answered Oct 13 '22 15:10

Nivesh