gpt4 book ai didi

node.js - res.redirect() 在 node.js 中不适合我

转载 作者:搜寻专家 更新时间:2023-10-31 22:43:43 25 4
gpt4 key购买 nike

我正在尝试发布对/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);
}
});
}
});

因此,除了重定向之外,一切正常。我在 Node 控制台中收到正确的 GET 请求,但浏览器中没有任何反应。 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。 View 引擎是 Handlebars。

感谢阅读!

最佳答案

我认为状态 200 让您失望。尝试使用 302,它应该可以工作。

res.writeHead(302, {
'Location': '/draft?id='+id
});
res.end();

关于node.js - res.redirect() 在 node.js 中不适合我,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20058356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com