res.redirect()在node.js中不适用于我

编程入门 行业动态 更新时间:2024-10-26 08:27:54
本文介绍了res.redirect()在node.js中不适用于我的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I am trying to POST a request for /draft and create a new "draft" / update an existing one in my database. after that I want to instantly redirect to the /draft?id=RELEVANT_ID_HERE page.

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

this is my current POST request function:

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请求,但是在浏览器中没有任何反应.

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

这是GET请求的代码:

this is the code for the GET request:

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和猫鼬.视图引擎是把手.

I am using Express and Mongoose. view engine is Handlebars.

感谢阅读!

推荐答案

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

I think the status 200 is throwing you off. Try using a 302 and it should work.

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

更多推荐

res.redirect()在node.js中不适用于我

本文发布于:2023-11-28 19:48:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1643726.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:适用于   中不   redirect   res   js

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!