Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS Express Root Path

In NodeJS Express module, specifying path "/" will catch multiple HTTP requests like "/", "lib/main.js", "images/icon.gif", etc

 var app = require('express')
 app.use('/', authenticate);

In above example, if authenticate is defined as followed

var authenticate = function(request, response, next) {
    console.log("=> path = " + request.path);
    next()
}

Then you would see

=> path = /
=> path = /lib/main.js
=> path = /images/icon.gif

Could anyone advise how to define path in Express "app.use" that only catch "/"?

like image 825
iwan Avatar asked Sep 02 '25 16:09

iwan


1 Answers

If you are trying to expose static files, people usually place those in a folder called public/. express has built-in middleware called static to handle all requests to this folder.

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

app.use(express.static('./public'));
app.use('/', authenticate);

app.get('/home', function(req, res) {
  res.send('Hello World');
});

Now if you place images/css/javascript files in public you can access them as if public/ is the root directory

<script src="http://localhost/lib/main.js"></script>
like image 79
aray12 Avatar answered Sep 05 '25 13:09

aray12