1

I'm using Node/Express and Jade to build and App.

I have a POST route that sanitize and validate form input and then save this to a MongoDB. If this form input is'nt validated, the route will throw and error and the error handler will re-render this same page...

And here come the problem. In this re-render and want the form values be pre written and ready to be corrected by the user... I don't want a clean form where the user has to re-write everything.

I have tried to submit the req.body (sanitized) data to the re-rendered page, which works. But if try to use this data in my Jade view, Node will output and error when this req.body data is not defined... Like when you enter this page for the first time, and have'nt entered any wrong inputs yet.

How do i solve this in a good way?

4

1 回答 1

1

编辑 -如果没有代码示例,我不确定我的示例是多于还是少于您的需要。

如果您在表单的 POST 请求处理程序中立即呈现表单模板,您可能不需要涉及req.session. 只需保存适当的局部变量并渲染您的模板。

如果您必须重定向或需要在多个请求中使用这些值,您可以将它们保存在req.session如下所示的位置。

无论哪种方式,请确保您的 Jade 模板能够处理所有情况;在我的示例中,我测试if(locals.savedValues)以决定是否将默认值或保存的值写入表单。

最后,如果错误与翡翠无关,请粘贴该错误。


使用 req.session 保存值。locals在呈现表单之前设置一个变量来表示保存的值或 null。

app.get('/form', function(req, res){
  res.locals.savedValues = req.session.savedValues || null;
  res.locals.savedErr = req.session.savedErr || null;
  res.render('form');
});

app.post('/form', function(req, res){
  var values = {
    name: req.body.name,
    email: req.body.email,
  };
  validateForm(values, function(err, processed){
    if(err){
      req.session.savedValues = processed; 
      req.session.savedErr = err;
      // req.session.savedValues = values, if you dont want to propose changes
      res.redirect('back');
    } else {
      delete req.session.savedValues;
      delete req.session.savedErr;
      res.redirect('/success');
    };
  });
});

在您的翡翠模板中,处理这两种情况:

if(locals.savedErr)
  span.error=locals.savedErr
form(action='form', method='post')
  if(locals.savedValues)
    input#name(type='text')=locals.savedValues.name
    input#email(type='text')=locals.savedValues.email
  else
    input#name(type='text')
    input#email(type='text')
于 2013-09-25T15:21:34.187 回答