我有一个表单,我正在将信息插入数据库。该部分工作得很好,但之后如何重定向到另一个页面?

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'; 
            })

请您参考如下方法:

引用here查看 Nodejs 的 http.Response API。 response.writeHead(statusCode[, statusMessage][, headers])

替换此行

redirect: '/home'; 

具有以下内容

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

重定向的状态码为3xx级别,示例中的302表示“找到” “Location” header 将给出重定向到的路径

如果用 Express 编写,请引用 here并使用

res.redirect([statusCode,] '/path') 

如果可选状态码没有明确表达,则默认为 302 'found'


评论关闭
IT源码网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!