简体   繁体   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}`})
        }
      }
    } 
    
  })
  
})

this is my code so far i have assigned this in the global:到目前为止,这是我的代码,我已将其分配给全局:

const dataPath = 'data.json';

and this is what the data.json file looks like这就是 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."
    }
  }
}

if i type in the command line http -v get:3000/api/notes/3, the error message statement executes when its suppose to execute the object with id 3如果我在命令行中键入 http -v get:3000/api/notes/3,则错误消息语句在假设执行 id 为 3 的 object 时执行

however when i delete the error message if statement.但是,当我删除错误消息 if 语句时。 the code can retrieve object from the json file how can i fix this?该代码可以从 json 文件中检索 object 我该如何解决这个问题?

The error you recieve您收到的错误

_http_outgoing.js:470 throw new ERR_HTTP_HEADERS_SENT('set'); _http_outgoing.js:470 抛出新的 ERR_HTTP_HEADERS_SENT('set'); ^ Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client ^ 错误 [ERR_HTTP_HEADERS_SENT]: 发送到客户端后无法设置标头

is because you use res.json() inside a for...in loop.是因为您在for...in循环中使用res.json() The first iteration will break the rest because it will send a response .第一次迭代将破坏 rest 因为它会发送响应

The res object represents the HTTP response that an Express app sends when it gets an HTTP request. res object 表示 Express 应用程序在收到 HTTP 请求时发送的 HTTP 响应。

you should manipulate data (object/array/collection) and then send it once outside the for...in loop.您应该操作数据(对象/数组/集合),然后在for...in循环之外发送一次。

something like this:像这样的东西:

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