res.redirect() не работает для меня в node.js
Я пытаюсь отправить запрос / черновик и создать новый "черновик" / обновить существующий в моей базе данных. после этого я хочу мгновенно перенаправить на страницу /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);
}
});
}
});
Итак, все работает, кроме перенаправления. Я получаю правильный запрос GET в консоли узла, но в браузере ничего не происходит.
это код для запроса 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');
}
});
Я использую Экспресс и Мангуст. Вид двигателя - Руль.
Спасибо за прочтение!
1 ответ
Я думаю, что статус 200 сбивает вас с толку. Попробуйте использовать 302, и он должен работать.
res.writeHead(302, {
'Location': '/draft?id='+id
});
res.end();