Skip to content

Instantly share code, notes, and snippets.

@naholyr
Last active October 29, 2020 21:46
Show Gist options
  • Save naholyr/f6a2903d72d495db6ab7 to your computer and use it in GitHub Desktop.
Save naholyr/f6a2903d72d495db6ab7 to your computer and use it in GitHub Desktop.
res.redirect not working as expected
node_modules

res.redirect does not support mount point as documented

The use case

Main app calls app.use('/mountpath', otherApp), then all redirects and locations in otherApp must be prefixed with /mountpath. As stated in documentation it's supposed to be supported right out of the box.

What the doc says

Extract from documentation:

This next redirect is relative to the mount point of the application. For example, if you have a blog application mounted at /blog, ideally it has no knowledge of where it was mounted. So, where a redirect of /admin/post/new would simply give you http://example.com/admin/post/new, the following mount-relative redirect would give you http://example.com/blog/admin/post/new:

res.redirect('admin/post/new');

What I do

app.use('/mountpath', otherApp);

otherApp.get('/url', function (req, res) {
  res.redirect('otherUrl');
});

What I expect

http://app/mountpath/url → Location: /mountpath/otherUrl

What I get

http://app/mountpath/url → Location: otherUrl

The demo

Run node server.js and curl http://localhost:3002/mounted/hello and see how you're redirected to world instead of /mounted/world.

var express = require('express');
var app = module.exports = express();
var mountedApp = require('./mounted-app');
app.use('/mounted', mountedApp);
var express = require('express');
var app = module.exports = express();
app.get('/hello', function (req, res) {
res.redirect('world');
});
app.get('/world', function (req, res) {
res.status(200).json({
"hello": "world"
});
});
{
"name": "test-express-redirect-mountpath",
"version": "1.0.0",
"description": "",
"main": "mounted-app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "https://gist.github.com/f6a2903d72d495db6ab7.git"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.8.8"
}
}
require('http').createServer(require('./app')).listen(3002).on('listening', function () {
console.log(this.address());
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment