I'm looking to get node (using express for routing) to resolve all occurrences of the ../ symbol in urls before performing any routing on the url.
For example if apache is queried at the url /a/b/../c/d/e/../../f, it will first resolve all the ../ symbols and will finally serve any content located at /a/c/f.
With node+express, however, /a/b/../c/d/e/../../f is taken literally and will not match routing for /a/c/f. My problem is that the following code will not respond to a request like /a/b/../c/d/e/../../f:
app.get('/a/c/f', function(req, res) {
return res.status(200).json({ msg: 'it worked!' });
});
How can I get node+express to resolve ../ symbols in the url?
Try adding (begore first app.get(...)) this middleware:
var path = require('path');
// some other code
app.use(function(req, res, next) {
var parsedPath = path.resolve(req.path);
var root = req.protocol + '://' + req.get('Host');
var redir = path.join(root, parsedPath);
console.log(redir);
if (parsedPath !== req.path) {
res.redirect(parsedPath);
} else {
next();
}
});
This should be not needed as express + node should resolve paths as you would expect.
You can use the path module to join the URL segments:
const path = require("path");
app.use(function(req, res, next) {
const pathArr = req.url.split("/");
req.url = path.join.apply(null, pathArr);
next();
});
Reassigning it to the url will allow any subsequent express matchers to continue processing it without having to take manual control of serving anything.