Search code examples
node.jsexpressresponsepage-refresh

express force refresh client webpage


Im trying to refresh a clients webpage (using a router) and everywhere I look I see something along the lines of using res.redirect(same page link of some sort), however for some reason this isnt working for me, do you know of any alternatives? my code looks something like this

    router.post('/sendSnippet', function (req, res) {
    req.on('data', function(data) {
        User.findOne({email: req.user.email}).then((userToEdit) =>{
            if(userToEdit){
                var newSnippet = {
                    "types":[],
                    "code": data.toString()
                }
                userToEdit.snippets.push(newSnippet)
                userToEdit.save().then(()=>{
                    //refresh here
                    res.redirect('/profile/');
                })
            }
        })
    })
});

thanks for any help in advance


Solution

  • Assuming you are trying to force-reload a client's browser tab for your website, I don't think you can do that server-side.

    You can use meta http-equiv or the Refresh HTTP header to tell the client's browser to refresh the page after some time or use client javascript to refresh the page:

    Router:

    router.post("/example", (req, res) => {
      res.header("Refresh", "10"); // tells the browser to refresh the page after 10 seconds
      res.send("your data");
    });
    

    Meta:

    <head>
      <!-- Refresh after 10 seconds -->
      <meta http-equiv="refresh" content="10">
    </head>
    

    Javascript + html:

    <html>
      <body>
        <script>
          // reloads after 10 seconds
          setTimeout(() => {
            location.reload();
          }, 10000);
          
          // or you could have some kind of API to tell when to refresh the page
          function check() {
            const x = new XMLHttpRequest();
            x.open("GET", "some path");
            x.send();
            x.onload = function() {
              if (x.response === "done") {
                location.reload();
              } else {
                setTimeout(check, 1000);
              }
            }
          }
          check();
        </script>
      </body>
    </html>