问题
What i want to know is whether is it possible to redirect from one route to another with data from first route to second one? For example from the HTML form i POST the data(say phone number) to a route (say '/route1') and with success operation at this route i want to send phone number to '/route2' from'route1'. If it is possible then how should I do that?
回答1:
There are a number of ways to pass data in a redirect.
- Put the data in a query parameter on the redirect URL
http://www.whatever.com/somePath?ph=123-456-1234
. Either the server or the client can access the data when rendering the redirected page. - Put the data in a server-side session object where it will be available when rendering the redirected page.
- Use a "flash" middleware which saves some data for only the "next" request from that particular browser so the data will be available server-side when rendering the redirected page.
Of these options, the first one is clean because its stateless and the data is available to either client or server. It doesn't require any temporary server-side storage either.
回答2:
What i want to know is whether is it possible to redirect from one route to another with data from first route to second one?
Once your data is posted without error, you can redirect the client that way :
// POST data
app.post('/oneRoute', function(req, res) {
let myData = new MySchema();
myData.phoneNumber = req.body.phoneNumber;
// save data to DB then redirect to /anotherRoute
myData.save(function(err) {
if (err) {
// error
} else {
// redirect path
res.redirect('/anotherRoute');
}
});
});
Then, if you want to pass the data in a query parameter on the redirect URL, you can :
(...)
} else {
// redirect path + query parameter
res.redirect('/anotherRoute?phonenumber='+req.body.phoneNumber);
}
(...)
What Next ? You can get the query string from the url of your redirected path...
http://localhost:3000/anotherRoute/?phonenumber=6876766242425
Note : as mentioned by jfriend00's reponse, this solution is clean and stateless, the data is available to either client or server.
See also res.redirect() & req.query
Session : in a different manner , if you want to store the data server-side, you can use Simple session middleware for Express package...
来源:https://stackoverflow.com/questions/51162321/is-there-any-way-of-redirecting-from-one-route-to-another-with-data-from-first-r