简体   繁体   English

通过 Express/Node.js 中的重定向将错误消息传递给模板

[英]Passing error message to template through redirect in Express/Node.js

In my Node.js application, I have a function (routed by Express) which presents a form to the user:在我的 Node.js 应用程序中,我有一个 function(由 Express 路由),它向用户显示了一个表单:

app.get('/register', function (req, res) {
  res.render('form');
});

I have another function, routed to the same URL, but which handles POST requests, which receives the data submitted by the previous form.我还有另一个 function,路由到同一个 URL,但它处理 POST 请求,它接收前一个表单提交的数据。 If the form does not validate, it redirects the user back to the form;如果表单未通过验证,它将用户重定向回表单; otherwise, it does what should be done:否则,它会做应该做的事情:

app.post('/register', function (req, res) {
  if (validate(req.registerForm)) return res.redirect('back');
  persistStuff(req.registerForm, function (err, data) {
    // Do error verification etc.
    res.redirect('back')
  });
});

What I want to do is to send a error message to be presented, in the line:我想要做的是在以下行中发送一条要显示的错误消息:

if (validate(req.registerForm)) return res.redirect('back');

To write something like写类似的东西

if (validate(req.registerForm)) return res.render('form', {msg:'invalid'});

is unacceptable because I want to follow the POST-REDIRECT-GET pattern.是不可接受的,因为我想遵循 POST-REDIRECT-GET 模式。 I could do something like我可以做类似的事情

if (validate(req.registerForm)) return res.redirect('/register?msg=invalid');

but it would hardcode an URL in my code and I'd prefer to avoid it.但它会在我的代码中硬编码一个 URL ,我宁愿避免它。 Is there another way to do it?还有另一种方法吗?

You need to use flash notifications , and it is built into express.您需要使用flash 通知,它内置在 express 中。

You'll add a message like so: req.flash("error", "Invalid form...");您将添加如下消息: req.flash("error", "Invalid form...");

You'll need a dynamic handler to add the messages to your rendered template, or you can check out the ones TJ has made for express.您需要一个动态处理程序来将消息添加到您呈现的模板中,或者您可以查看 TJ 为 express 制作的消息。 ( express-messages ) 快讯

You could simply have it redirect as res.redirect('..?error=1')您可以简单地将其重定向为res.redirect('..?error=1')

the?这? tag tells the browser that it is a set of optional parameters and the.. is just a pathname relative recall (like calling cd.. on terminal to move back one directory) and you're browser will direct to the appropriate page with that tag at the end: http://.....?error=1标签告诉浏览器它是一组可选参数,而.. 只是一个路径名相对调用(如在终端上调用 cd.. 以移回一个目录),您的浏览器将使用该标签定向到相应的页面最后: http://.....?error=1

then you can simply pull the error on the appropriate page by doing a:然后您可以通过执行以下操作简单地在相应页面上拉出错误:

if (req.param("error" == 1)) { // do stuff bassed off that error match };

you can hardcode in several different error values and have it respond appropriately depending on what error occurred您可以硬编码几个不同的错误值,并根据发生的错误做出适当的响应

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM