Reputation: 18
i am new to node js and was making a mini message board as a assignment. What I want to do is to redirect the user to localhost:3000/index from localhost:3000/new when "submit" is pressed.I have tried using res.redirect but it is not working.
Here's the code:-
router.get('/', function(req, res, next) {
res.render('index', {
title: 'MINI-MESSAGE-BOARD',
message: messages
});
});
router.post('/new', function(req, res, next) {
var userMessage=req.body.messagesName;
var userName=req.body.userName;
res.render('new');
messages.push({
name: userName,
text: userMessage,
date: new Date()
});
res.redirect('/index');
});
module.exports = router;
I have a messages array declared above.
I have also created a form in pug for new.js which is:
form(action="/new" method="POST" redirect="/index")
input(type="text" placeholder="write something" name="userName")
br
br
input(type="text" placeholder="write something" name="messagesName")
button(value="SUBMIT")
I've tried giving a href to button(out of desperation)still didn't worked.
Thank you very much in advance.
Upvotes: 0
Views: 310
Reputation: 74680
Express can't render a response and then redirect as they each send different HTTP response headers to the client. You can do one or the other.
Remove the res.render()
router.post('/new',function(req,res,next){
var userMessage=req.body.messagesName;
var userName=req.body.userName;
messages.push({name:userName,text:userMessage,date: new Date()});
res.redirect('/index');
});
Upvotes: 1