繁体   English   中英

express js条件app.get()语句

[英]express js conditional app.get() statement

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 的 object 时执行

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

您收到的错误

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

是因为您在for...in循环中使用res.json() 第一次迭代将破坏 rest 因为它会发送响应

res object 表示 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}`})
      }
    }
  });
  
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM