nodejs/express include local js file
ReasonNode.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 filesapp.use(express.static(path.join(__dirname, 'public')));app.get('/', function(req, res) { res.redirect('index.html');});app.listen(8080);
As Tomasz Kasperek pointed out, you need to let Express know that you intend to host these files in a static directory. This is technically called defining static middleware.
This should look something like:
var express = require('express');var app = express();// first parameter is the mount point, second is the location in the file systemapp.use("/public", express.static(__dirname + "/public"));
It's super simple and I suggest you go the route of making some sort of public
folder, rather than bothering to make specific files and folders static.
Then the files would simply be referenced like so from the root index.html
:
<link href="public/css/reset.css" rel="stylesheet" type="text/css">
Hope this helps you!
I got it to work by using this syntax
app.use(express.static('public'));
Copy the css and js files under the 'public' directoryand then add the reference in the index.html file
<link rel="stylesheet" href="/css/reset.css">