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

后端 未结 9 1312
孤街浪徒
孤街浪徒 2020-12-29 19:41

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

相关标签:
9条回答
  • 2020-12-29 20:15

    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

    0 讨论(0)
  • 2020-12-29 20:23

    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/

    0 讨论(0)
  • 2020-12-29 20:23

    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

    0 讨论(0)
  • 2020-12-29 20:27

    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);
    
    0 讨论(0)
  • 2020-12-29 20:29

    Express 4.x+ answer:
    res.redirect(req.path)

    0 讨论(0)
  • 2020-12-29 20:30

    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.

    0 讨论(0)
提交回复
热议问题