Can't redirect using res.redirect(), express + NodeJS

Issue

I am building my first app in Node.js. Everything was going fine until now. I am facing a problem while trying to redirect using server-side code in Node.js application doesn’t throw any error, but on the browser it stays on the same page and doesn’t redirect to chatroom page from the index page.

Index.js

var express = require('express');
var router = express.Router();
var obj = require('../bin/www');
var db = require('../databaseModels');

/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express Chat' });
});

//here we will save the username of the New user
router.post("/setUserName", async function(req,res) {
try{
    var newUser = new db.Users(req.body);
    await newUser.save()
    //Emit the event that a new user has joined the chat
    obj.io.emit("newUserJoined", req.body)
    return res.redirect(301,"http://192.168.34.54:4747/chatroom");
}
catch(error) {
    res.sendStatus(500);
    console.log(error);
}
})

module.exports = router;

chatroom.js

var express = require('express');
var router = express.Router();
var obj = require('../bin/www');
var db = require('../databaseModels');

/* GET users listing. */
router.get('/', function(req, res, next) {
    res.render('chatroom', {title: 'Welcome to Chat Room'});
});

module.exports = router;

Solution

Use your ‘chatroom’ router in bin/www like you have used ‘index’ router.

app.use('/chatroom',chatroom);

and in index router, use relative paths while calling the chatroom router.

return res.redirect(301,"/chatroom");

Answered By – Ratish Udawat

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published