Reload a page after res.redirect('back') i

2019-02-20 10:24发布

问题:

I'm working on an application which allows you to upload images, and create albums. Everything works fine accept that after an album is created the new album isn't shown in the client until the page is reloaded, and I can't figure out how to solve this.

Below is the route for creating an album. Is it somehow possible to use something else than res.redirect('back') in this case so that the page is reloaded after the route has finished?

Of course I could copy/paste the code from the route for loading the page in the first place, but that would be to much DRY. Maybe I can call the other route from within this route?

route:

app.post('/album', function(req, res){

    var newAlbum = new albumModel.Album();

    newAlbum.imageName = req.body.albumPicsName;
    newAlbum.imageId = req.body.albumPicsId;
    newAlbum.title = req.body.albumTitle;

    newAlbum.save(function (err) {
        if (err) {
            console.log(err);
            // do something
            console.trace();
        }
        res.redirect('back');
    });
});

回答1:

You should be able to do res.redirect('/album') instead of back to force a full reload but get the same type of feedback.



回答2:

'back' is an alias for req.get('Referrer') so if '/albums' is your referrer you might still experience issues with the browser returning a 304 (http not modified) http status or a browser cached page (common). If you experience that issue you can do a couple of things:

Send some cache clearing headers:

res.header('Cache-Control', 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0');
res.redirect('back');

Or modify the url:

 var url = require('url');
 var u = url.parse(req.get('Referrer'), true, false);
 u.query['v'] = +new Date(); // add versioning to bust cache 
 delete u.search;
 res.redirect(url.format(u));  

Of course if you know the url such as '/albums' you don't have to go though all that rigamarole to add some versioning - just append current timestamp to the url string.

The first way is cleaner and works better imo. I've seen cases when a page doesn't have a referrer even though I clearly came from another page due to caching.