Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js with express how to remove the query string from the url

I have a button that is performing a get to my page and adding a filter to the query string. My code applies that filter to the grid but the user can remove/edit that filter. Since they can see what filter was applied in the grid, I would like to remove the ?filter=blah from the query string when the page is displayed.

It might be confusing if on the page and the URL says ?filter=columnA which is correct initially, but the user removes that filter and applies a new one on columnB but the query string still says ?filter-columnA. The grid can handle changing filters without needing a post back.

How can I do that? And if you cannot remove/update a query string, is it possible to parse it and then just redirect to the main page without the query string? Once I have the filter saved to var filter, I no longer need it in the query string.

here is the code that displays the page:

exports.show = function(req, res) {     var filter = req.query.filter;     if (filter === null || filter === "") {         filter = "n/a";     }          res.render("somepage.jade", {             locals: {                 title: "somepage",                 filter: filter             }     });  }; 
like image 963
dan27 Avatar asked Jan 04 '13 23:01

dan27


People also ask

How do you separate a query string from a URL?

The query string is composed of a series of field-value pairs. Within each pair, the field name and value are separated by an equals sign, " = ". The series of pairs is separated by the ampersand, " & " (or semicolon, " ; " for URLs embedded in HTML and not generated by a <form>...

How do I remove values from a URL?

Just pass in the param you want to remove from the URL and the original URL value, and the function will strip it out for you. To use it, simply do something like this: var originalURL = "http://yourewebsite.com?id=10&color_id=1"; var alteredURL = removeParam("color_id", originalURL);

How do I pass a query string in node JS?

querystring.parse() Method parse() method is used to parse the URL query string into an object that contains the key value pair. The object which we get is not a JavaScript object, so we cannot use Object methods like obj. toString, or obj.


2 Answers

Use url.parse() to get the components of your address, which is req.url. The url without the query string is stored in the pathname property.

Use express' redirect to send the new page address.

const url = require('url'); // built-in utility res.redirect(url.parse(req.url).pathname); 

Node docs for url.

like image 168
Constantine Turtsevich Avatar answered Sep 19 '22 12:09

Constantine Turtsevich


Don't use a module for doing something like that:

res.redirect( req.originalUrl.split("?").shift() ); 
like image 43
Tim Avatar answered Sep 16 '22 12:09

Tim