开发者

Express.JS Handling Server-Side Errors

开发者 https://www.devze.com 2023-02-20 05:00 出处:网络
I\'m using Express.JS on Node.JS for an application I\'m building. I am setting up routes and doing my best to maintain a RESTful architecture.

I'm using Express.JS on Node.JS for an application I'm building. I am setting up routes and doing my best to maintain a RESTful architecture.

What is the process for accepting form input, encountering an error of some sort (not necessarily a validation error) and then showing the user the same form, but including the data they sent to the server in the first place?

At first, I stored the POST data to a session, but this never felt like it was a good solution, more like a hack.

Then I adjusted my routes, and instead used app.post|put|del() to handle the form submission, then using a route with app.all() that would be used as a "catch-all". Basically, if I encountered an error, I would call next(), handling control back to my "catch-all" route. This ended up causing me to deviate from my original RESTful approach.

Now, I've set up my routes to mirror a RESTful approach more accurate开发者_运维百科ly. However, if I use app.redirect(), the data is lost in the redirect. I've ended up using what feels like another hack: controller.new_form.apply(this, arguments); (this is called within controller.create())

Of course I could use client-side validation, but I'm doing my best to create an app that works completely server-side first, then adding client-side code as a way to improve the user experience where it's supported.

Is there some method available to express.js (or connect.js) that accepts the form action on a different URI from the form itself, but allows me to go back without actually redirecting the browser so the form can remain populated (as well as displaying an error messoge) for my users?


Couldn't you just call res.render with a different template depending on success or failure? So if all the POSTed form data validates, proceed to res.render 'thankyou.jade' otherwise do res.render 'form.jade' again? This is similar to what kcbanner suggests, just without defining distinct methods for each one, although that is a nice thing to do if you have any special logic in there.


You can call views from other views, just pass in req and res.

Example:

exports.index = function(req, res) {
  res.render('index');
};

exports.verify = function(req, res) {
  res.local('flash', 'Set a template local variable');
  exports.index(req, res);
};

Here I set template local in one view, and then call another view to actually handle the response. You could call your get handler in your post handler.

0

精彩评论

暂无评论...
验证码 换一张
取 消