开发者

How can I Post-redir-get without losing form data

Let's say a user gets a page /form/

GET /form/

He then fills in the form and sends a post request

POST /form/

The server attempts to validate user input and determines input to be invalid.

Currently the history chain for the users is

  • GET /form/
  • POST /form/

Now the server redirects the user to the GET /form/ page so it can fill in the form again (with error messages).

His history looks like

  • GET /form/ with filled in form fields
  • GET /form/ without filed in form fields

How do I send the user back without the user losing the details he entered in his first form?

What techniques are there for redirecting users back to their GET /form/ page and not forcing them to re-enter their information.

Below is my express (node.js) specific server side code for this example.

The validation middleware:

validate().on("error", function _error(msg) {
    // store error message on request object
    req.flash(msg, validateUserMessage[msg]);
}).on("valid", function _valid() {
    // handle the rest of /POST/
    next();
}).on("invalid", function _invalid() {
    // redirect user back to last page, the /GET/ form
    res.redirect("back");
}).run(function _validateUsers(check, sanitize) {
    // validation logic.
}); 

The routing:

// GET /form/
app.get("/form", function _signUpView(req, res) {
    // render /form/
    res.render("auth/signup", req.flash());
});

// POST /form/
// validation middleware used here. 
app.post("/f开发者_高级运维orm", secure.validateUser, function _signUpCreate(req, res) {
    model.create(req.body, function _create() {
         // create thing in database
    });
});


DO NOT redirect on invalid input. Do it on valid input only.

On invalid input, respond to the POST request with the same form, but this time populated with the POST data that you just received.


I have decided to summarise the comments below into my answer:

To me, there seems to be only two sure ways of doing this:


1. Passing the user input parameters back from the server to the browser and repopulate the form either:

   a) Using a parameters object passed to the view and populating each field using your severside language

   b) Passing back a Json object and populating the form using loadJson



2. Using HTML5 local storage - which also requires JavaScript


If you do not persisit your data using either the server or JavaScript, then surely you are limiting yourself to relying on the browser - which is something you have no control over.

Good luck - if you do find a solution then please post it as your answer as I would be very intersted to see how you succeeded.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜