Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rewrite url path using node.js

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';

But the url continues the same

like image 604
Rafael Motta Avatar asked Nov 19 '12 00:11

Rafael Motta


People also ask

How do I find the node of a URL?

The node number can also be found in Content or Find content. Go to the Express toolbar and select Content (or go to the Shortcuts toolbar and select Find content). Hover your mouse over one of the edit links. Down in the bottom-left corner of the browser, you'll see the URL for the link which contains the node number.

What is middleware express?

js is a routing and Middleware framework for handling the different routing of the webpage and it works between the request and response cycle. Middleware gets executed after the server receives the request and before the controller actions send the response.


1 Answers

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).

like image 196
David Weldon Avatar answered Sep 19 '22 07:09

David Weldon