I have a question on best practices for redirecting to a page and supplying an error message. For example, a person is registering as a new user and the username they have chosen is already in use. I want to redirect them back to the register page (basically a form), but display an error message. Should I set a cookie in the routing code and have javascript display the error or is there a best practice for this?
router.post('/register', function(req, res) {
var username = req.body.username;
db.fetchUser(username, function(err, user){
if (!err && !user) {
db.addUser(req.body.username, req.body.password, "vendor", function(err) {
if (!err) {
res.redirect('/portal');
}
else {
// TODO: Set error.
res.redirect('/register');
}
}
}
else {
// return error already exists.
res.redirect('/register');
}
});
});
I wound up using express-session, which seems a clean way to do it.
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var routes = require('./routes/index');
var portal = require('./routes/portal');
var FileStore = require('session-file-store')(session);
var app = express();
app.use(session({
secret: "flibbernachosqueezance",
store: new FileStore,
saveUninitialized: true,
resave: true
}));
And then using things like this for the session variables:
req.session.userMessage = "This username already exists: "+username;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.