In App redirect in expressjs using middleware
Asked Answered
S

2

11

I am trying to make a middleware for handling url aliases, what I am doing right now is :

// [...]
module.exports = function() {
  
  return function(req, res, next) {
    // getAlias would get an object {alias:"alias/path",source:"/real/path"} or null
    var alias = getAlias(req.url);
    if(alias) {
        req.url = alias.source;
    }
    next();
  };

};

I am looking in a store for the requested url and if it is found as an alias I change request.url to the source path to that alias so that express calls the right route.

The problem is request.url and request.path have the same value, but changing request.path does not work while request.url works. In addition I am not sure which one i have to test agains.

Things work when I interact with request.url but just wanted to make sure that I am doing it the proper way.

Any thoughts?

Sequent answered 29/9, 2013 at 15:0 Comment(0)
G
13

Rewriting the req.url property is the correct way for internally rerouting requests. That is why there is a req.originalUrl for the cases where one does change the original URL.

This is what the Express documentation states for req.originalUrl:

This property is much like req.url, however it retains the original request url, allowing you to rewrite req.url freely for internal routing purposes.

The req.url property isn't documented, but from the statement above you can infer it's meant to be used in the way you explained. It is also used in that way in some of the Express tests.

Geognosy answered 29/9, 2013 at 15:31 Comment(1)
This does not seem to work from inside express mini router (using express.Router())Chatoyant
D
0

You can use run-middleware module exactly for that. Just run the handler you want by using the URL & method & data.

https://www.npmjs.com/package/run-middleware

For example:

module.exports = function() {

  return function(req, res, next) {
    // getAlias would get an object {alias:"alias/path",source:"/real/path"} or null
    var alias = getAlias(req.url);
    if(alias) {
        res.runMiddleware(alias,(status,data)=>(res.status(status).send(data))
    }
    next();
  };

};
Desinence answered 15/9, 2016 at 9:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.