`Confirm Form Resubmission` issue on page rendered

2019-06-05 08:12发布

问题:

html contains

form(name="Form", action="/", method="post")
  button(type='submit') submit

Express server contains:

app.post('/', function(req, res){   
  res.render('home', {user: req.body});
});

As expected the home.jade is rendered in the browser. But when I refresh the home.jade file at http://localhost:3000 It asks for Confirm Form Resubmission I want to get rid of this - Confirm Form Resubmission!

The home.jade file is simple file containing simple text.

回答1:

The problem isn't really caused by your code, but by that browsers want to do a post again when you've received a response from a POST. A common way to solve this issue is to redirect to the same page.

app.post('/', function(req, res){   
  res.redirect('/');
});

Now when you refresh the browser will refetch a GET '/' instead.

Update to reflect updated question

To render data that was posted on the redirected page, one can use sessions.

app.use(express.cookieSession());

app.post('/', function(req, res){
  req.session.user = req.body;
  res.redirect('/');
});

And in the middleware for GET '/' you have to make sure to use that parameter

app.get('/', function(req, res){
  res.render('home', { user: req.session.user });
});