解决“Cannot set headers after they are sent to the client”及异步问题

阅读: 评论:0

解决“Cannot set headers after they are sent to the client”及异步问题

解决“Cannot set headers after they are sent to the client”及异步问题

问题


NodeJs+express+mongoDB接口中,在循环中写`res.json`时会报错(Cannot set headers after they are sent to the client

 解决方法

  • 循环外面定义一个变量为`false`
  • 在循环中要写`res.json`的地方让其变为`true`
  • 在循环外面判断该变量为`true`时写`res.json`

具体代码实现

var isShow = false;   //定义开关变量
//loadcurr为数组,具体内容省略了
loadcurr.forEach(item => {Stock.findOneAndUpdate({             //Stock是用来连接数据库集合的_id: ObjectId(item._id)}, {$set: {//此处省略要修改的内容。。。。。。}},function (err, data) {if (err) {console.log(err)} else {//此处应该写res.json,但是为了解决报错让前面定义的变量为trueisShow = trueconsole.log('1', isShow);}})
})
console.log('2', isShow);
if (isShow == true) {res.json({status: "200"})
}


这样就可以成功解决Cannot set headers after they are sent to the client的错啦!!!

注意:

如果上面的代码执行顺序是先打印了console.log('2', isShow);后打印console.log('1', isShow);,说明存在异步,因此用异步解决即可,具体实现如下所示(若顺序是先执行console.log('1', isShow);后执行console.log('2', isShow);就是正确的):

  • 若返回值不是promise用以下方法
var isShow = false;(async function(){await new Promise((resolve, reject) => {//loadcurr为数组,具体内容省略了loadcurr.forEach(item => {//Stock是用来连接数据库集合的Stock.findOneAndUpdate({_id: ObjectId(item._id)}, {$set: {//此处省略要修改的内容。。。。。。}},function (err, data) {if (err) {console.log(err)} else {resolve(isShow = true)console.log('1', isShow);}})})})console.log('2', isShow);if (isShow == true) {res.json({status: "200"})}})()

 

  • 若返回值是promise用以下方法
var isShow = false;(async function(){//loadcurr为数组,具体内容省略了await loadcurr.forEach(item => {//Stock是用来连接数据库集合的_id: ObjectId(item._id)}, {$set: {//此处省略要修改的内容。。。。。。}},function (err, data) {if (err) {console.log(err)} else {isShow = trueconsole.log('1', isShow);}})})console.log('2', isShow);if (isShow == true) {res.json({status: "200"})}})()

 
好啦,以上就是解决循环里面写res.json报错问题及解决异步问题!在这两个问题没少费工夫??????

有问题欢迎指出,若有更好的解决方案欢迎在下面??????分享哦!!!

本文发布于:2024-02-02 10:35:34,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170684133343233.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:set   headers   client
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23