res.redirect() 在 Node.js 中对我不起作用

2023-12-30

我正在尝试发布 /draft 请求并创建一个新的“草稿”/更新我的数据库中的现有草稿。之后我想立即重定向到 /draft?id=RELEVANT_ID_HERE 页面。

这是我当前的 POST 请求功能:

app.post('/draft', function(req,res){
var id = req.query.id;
var postTitle = req.body.head;
var article = req.body.article;

if(id){
    db.postCatalog.findOneAndUpdate({_id: id}, {title:postTitle, inShort:article.substring(0,100), content:article}, function(err, data){
        if (err) {
            return handleError(err);
        }
        else {
            console.log(data);
            res.status(200).redirect('/draft?id='+id);
        }
    });
}
else{
    id = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
        return v.toString(16);
    });

    new db.postCatalog({title:postTitle, 
                    _id:id, 
                    author:'temp', 
                    AuthorID:2, 
                    date:'2/3/12', 
                    inShort:article.substring(0,100), 
                    content:article ,
                    published:false
                }).save(function (err, data) {
                    if (err) {
                        return handleError(err);
                    }
                    else {
                        console.log(data);
                        res.status(200).redirect('/draft?id='+id);
                    }
                });
}
});

so, everything works except for the redirect. I am getting the correct GET request in the node console, but nothing happens in the browser. node console log

这是 GET 请求的代码:

app.get('/draft', function(req,res){
var id = req.query.id;
if(id){
    db.postCatalog.findOne({_id: id}, function(err, post){
        if(err) {
            return handleError(err);
        }
        else{
            if(post){
                console.log(post);
                res.status(200).render('editDraft.hbs', {post: post}); 
            }
            else{
                routes._404(req,res);
            }
        }   
    });
}
else{
    console.log('creating new draft');
    res.status(200).render('editDraft.hbs');
}
});

我正在使用 Express 和 Mongoose。视图引擎是Handlebars。

谢谢阅读!


我认为状态 200 让你感到厌烦。尝试使用 302,它应该可以工作。

res.writeHead(302, {
    'Location': '/draft?id='+id
});
res.end();  
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

res.redirect() 在 Node.js 中对我不起作用 的相关文章

随机推荐