Rewrite url path using node.js

后端 未结 3 1711
名媛妹妹
名媛妹妹 2020-12-16 14:26

Is it possible to rewrite the URL path using node.js?(I\'m also using Express 3.0)

I\'ve tried something like this:

req.url = \'foo\';
相关标签:
3条回答
  • 2020-12-16 14:37

    A good idea should be to update the path too. My method suggestions:

    app.use(function(req, res, next) {
        console.log("request", req.originalUrl);
        const removeOnRoutes = '/not-wanted-route-part';
        req.originalUrl = req.originalUrl.replace(removeOnRoutes,'');
        req.path = req.path.replace(removeOnRoutes,'');
        return next();
    });
    

    By this way /not-wanted-route-part/users will became /users

    0 讨论(0)
  • 2020-12-16 14:47

    Sure, just add a middleware function to modify it. For example:

    app.use(function(req, res, next) {
      if (req.url.slice(-1) === '/') {
        req.url = req.url.slice(0, -1);
      }
      next();
    });
    

    This function removes the trailing slash from all incoming request URLs. Note that in order for this to work, you will need to place it before the call to app.use(app.router).

    0 讨论(0)
  • 2020-12-16 14:50

    you need override some properties of req (IncomingMessage in NodeJs):

    • url
    • path
    • search
    • query

    2

    function changeUrl(req, url) {
        const parsedUrl = new URL(url);
        req.url = url;
        req.originalUrl = url;
        req.path = parsedUrl.pathname;
        req.search = parsedUrl.search;
        req._parsedUrl = parsedUrl;
        const query = {};
        for(const entry of parsedUrl.searchParams) {
            query[entry[0]] = entry[1];
        }
        req.query = query;
    }
    
    0 讨论(0)
提交回复
热议问题