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 fil
Use req.path
If your endpoint is http://<your-domain>.com/hello/there?name=john
...
then req.path
= /hello/there
Documetation: https://expressjs.com/en/api.html#req.path
In order to avoid reload the page by forcing a redirect, I added the following to the <head>
section of my .ejs file:
<script type="text/javascript">
var uri = window.location.toString();
if (uri.indexOf("?") > 0) {
var clean_uri = uri.substring(0, uri.indexOf("?"));
window.history.replaceState({}, document.title, clean_uri);
}
</script>
Source: http://atodorov.org/blog/2013/01/28/remove-query-string-with-javascript-and-html5/
use this method to remove specific query parameter from URL.
/**
* remove query parameters from actual url
* @param {*} params paramerters to be remove, e.g ['foo', 'bar']
* @param {*} url actual url
*/
function removeQueryParam(parameters = [], url) {
try {
var urlParts = url.split('?');
var params = new URLSearchParams(urlParts[1]);
parameters.forEach(param => {
params.delete(param);
})
return urlParts[0] + '?' + params.toString();
} catch (err) {
console.log(err);
return url;
}
}
console.log(removeQueryParam(["foo"], "/foo?foo=foo&bar=bar"));
Above example will return /foo?bar=bar
The full url is stored in req.url
in your case, use node.js's url.parse() to pull out the parts. Take the path and send a Location header using res.set()
to redirect to URL without the query string.
var url = require('url');
res.set('Location', url.parse(req.url).pathname);
Express 4.x+ answer:
res.redirect(req.path)
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.