首页 > 解决方案 > express js条件app.get()语句

问题描述

app.get('/api/notes/:id', (req, res, next) => {
  fs.readFile(dataPath, 'utf-8', (err, data) => {
    if (err) {
      throw err;
    }
    const wholeData = JSON.parse(data);
    const objects = wholeData.notes;
    const inputId = parseInt(req.params.id);

    if (inputId <= 0) {
      res.status(400).json({error: 'id must be a postive integer'});
    } else {
      for (const key in objects) {
        if (parseInt(objects[key].id) === inputId) {
          res.status(200).json(objects[key])
        } if (parseInt(objects[key].id) !== inputId) {
          res.status(404).json({error: `bruh theres no id ${inputId}`})
        }
      }
    } 
    
  })
  
})

到目前为止,这是我的代码,我已将其分配给全局:

const dataPath = 'data.json';

这就是 data.json 文件的样子

{
  "nextId": 5,
  "notes": {
    "1": {
      "id": 1,
      "content": "The event loop is how a JavaScript runtime pushes asynchronous callbacks onto the stack once the stack is cleared."
    },
    "2": {
      "id": 2,
      "content": "Prototypal inheritance is how JavaScript objects delegate behavior."
    },
    "3": {
      "id": 3,
      "content": "In JavaScript, the value of `this` is determined when a function is called; not when it is defined."
    },
    "4": {
      "id": 4,
      "content": "A closure is formed when a function retains access to variables in its lexical scope."
    }
  }
}

如果我在命令行中键入 http -v get :3000/api/notes/3 ,则错误消息语句在假设执行 id 为 3 的对象时执行

但是,当我删除错误消息 if 语句时。代码可以从 json 文件中检索对象我该如何解决这个问题?

标签: javascriptexpress

解决方案


您收到的错误

_http_outgoing.js:470 抛出新的 ERR_HTTP_HEADERS_SENT('set'); ^ 错误 [ERR_HTTP_HEADERS_SENT]: 发送到客户端后无法设置标头

是因为您res.json()for...in循环中使用。第一次迭代将打破其余的,因为它会发送一个响应

res 对象表示 Express 应用程序在收到 HTTP 请求时发送的 HTTP 响应。

for...in您应该操作数据(对象/数组/集合),然后在循环外发送一次。

像这样的东西:

app.get('/api/notes/:id', (req, res, next) => {
  fs.readFile(dataPath, 'utf-8', (err, data) => {
    if (err) {
      throw err;
    }
    const wholeData = JSON.parse(data);
    const objects = wholeData.notes;
    const inputId = parseInt(req.params.id);

    if (inputId <= 0) {
      res.status(400).json({error: 'id must be a postive integer'});
    } else {
      let obj= false;
      for (const key in objects) {
        if (parseInt(objects[key].id) === inputId) {
          obj = objects[key];
        }
      }
      if (obj) {
        res.status(200).json(obj)
      } else 
        res.status(404).json({error: `bruh theres no id ${inputId}`})
      }
    }
  });
  
});

推荐阅读