tonejac
tonejac

Reputation: 1103

Add a trailing "/" to URL with Express Static

I'm using Express Static node server and have the following server.js code:

var express = require('express');

var app = express();
var fs        = require('fs');
var publicdir = __dirname + '/client';

app.set('port', 8080);


app.use(function(req, res, next) {
    if (req.path.indexOf('.') === -1) {
        var file = publicdir + req.path + '.html';

        fs.exists(file, function(exists) {
            if (exists)
                req.url += '.html';
                next();
            });
    } else {
        next();
    }
});
app.use(express.static(publicdir));

// Listen for requests
var server = app.listen(app.get('port'), function() {
    var port = server.address().port;
    console.log('Magic happens on port ' + port);
});

I'm currently trimming off the .html from the file names to clean up the URLs (eg, mysite.com/blog-article-title). The last step I'd like to do is to make it so it adds a trailing "/" to the URL, but I'm not sure how to do it. (eg, mysite.com/blog-article-title/).

Upvotes: 1

Views: 66

Answers (1)

Burdy
Burdy

Reputation: 611

Express Routing

var express = require('express');
var app = express();
var fs        = require('fs');
var path = require('path');
app.set('port', 3001);
app.use(express.static(path.join(__dirname, 'client')));
app.get('/blog-article-title/', function(req, res) {
    res.sendFile("blog-article-title.html");
})
var server = app.listen(app.get('port'), function() {
    var port = server.address().port;
    console.log('Magic happens on port ' + port);
});

Upvotes: 0

Related Questions