Omorhefere imoloame Omorhefere imoloame - 1 month ago 4
Node.js Question

How can I redirect to another page after I post data to my database?

I have a form and I'm inserting information into the database. That part works perfectly fine but how do I redirect to another page after that?



app.post('/create', function (req, res) {
Room.findOne({'name' :req.body.name}, function(err,room){
if(err){
return done(err);
}

if(room){
return done(null,false,req.flash('this room name is taken'));
}else{
var newRoom = new Room();
newRoom.name = req.body.name;
newRoom.topic = req.body.topic;
newRoom.participants = req.body.participants;
newRoom.type = req.body.type;
}
newRoom.save(function(err){
if (err){
throw err;
}
redirect: '/home';
})




Answer

Reference here to review http.Response API for nodejs. response.writeHead(statusCode[, statusMessage][, headers])

replace this line

redirect: '/home';

with the following

res.writeHead(302,{
            'Location':'/path',
        });
        res.end();

The status code for redirecting is 3xx level, 302 in the example is for 'found' The 'Location' header will give the path to redirect to

Comments