【问题标题】:Express Route foreach and if/else statment give me both if and else responseExpress Route foreach 和 if/else 语句给我 if 和 else 响应
【发布时间】:2020-08-20 14:57:45
【问题描述】:

//Modules
const express = require('express'); 

//Initializing
let router = express.Router()

//Midlewares
router.use(express.json())

//My Vacumms
let acs = [
  {
    id:1,
    name:"acs1",
    actionType:{
      state:false,
      temperature:1
    }
  },
  {
    id:2,
    name:"acs2",
    actionType:{
      state:false,
      temperature:1
    }
  },
  {
    id:3,
    name:"acs3",
    actionType:{
      state:false,
      temperature:1
    }
  }
]

//Main Page /Vacuums
router.get('/:id/:actionType/:OfOn', (req, res)=>{
  let Adress = req.params
  new Promise
  acs.forEach(Vacu =>{
    if(Adress.id == parseInt(Vacu.id)){
      for(type in Vacu.actionType){
          if(Vacu.actionType[type] == Vacu.actionType[Adress.actionType]){
            Vacu.actionType[type] = Adress.OfOn
            res.json(acs)
          }else if(Vacu.actionType[Adress.actionType] == undefined){
            res.json("Action type not found")
          }
      }
    }else{
      console.log("Wtf is going on!!! D:D::DD::D:D");
    }
  })
  
})

module.exports = router

错误:错误 [ERR_HTTP_HEADERS_SENT]:无法设置标头后 发送给客户端 在 ServerResponse.setHeader (_http_outgoing.js:526:11) 在 ServerResponse.header (C:\Users\Desktop\NodeTutorial\HomeWork2\node_modules\express\lib\response.js:771:10) 在 ServerResponse.send (C:\Users\Desktop\NodeTutorial\HomeWork2\node_modules\express\lib\response.js:170:12) 在 ServerResponse.json (C:\Users\Desktop\NodeTutorial\HomeWork2\node_modules\express\lib\response.js:267:15) 在 C:\Users\Desktop\NodeTutorial\HomeWork2\Routers\acs.js:49:17 在 Array.forEach () 在 C:\Users\Desktop\NodeTutorial\HomeWork2\Routers\acs.js:42:7 在 Layer.handle [as handle_request] (C:\Users\Brian\Desktop\NodeTutorial\HomeWork2\node_modules\express\lib\router\layer.js:95:5) 在下一个(C:\Users\Desktop\NodeTutorial\HomeWork2\node_modules\express\lib\router\route.js:137:13) 在 Route.dispatch (C:\Users\Desktop\NodeTutorial\HomeWork2\node_modules\express\lib\router\route.js:112:3) wtf正在进行中!!! D:D::DD::D:D Wtf 进行中!!! D:D::DD::D:D

当我使用 Postman 进行测试时,一切正常,但我仍然遇到这些错误... 我不知道我出了什么问题!

//我想用request.params通过地址栏来操作我的acs数组!

【问题讨论】:

    标签: javascript express


    【解决方案1】:

    通常当您尝试响应两次时会发生这种情况。我认为,这个循环中的那个问题。发送响应后尝试打破循环

      if(Adress.id == parseInt(Vacu.id)){
      for(type in Vacu.actionType){
          if(Vacu.actionType[type] == Vacu.actionType[Adress.actionType]){
            Vacu.actionType[type] = Adress.OfOn
            res.json(acs)
            break
          }else if(Vacu.actionType[Adress.actionType] == undefined){
            res.json("Action type not found")
            break
          }
      }
    

    【讨论】:

      猜你喜欢
      • 2014-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多