简体   繁体   中英

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

{
  "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

however when i delete the error message if statement. the code can retrieve object from the json file how can i fix this?

The error you recieve

_http_outgoing.js:470 throw new ERR_HTTP_HEADERS_SENT('set'); ^ Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

is because you use res.json() inside a for...in loop. The first iteration will break the rest because it will send a response .

The res object represents the HTTP response that an Express app sends when it gets an HTTP request.

you should manipulate data (object/array/collection) and then send it once outside the for...in loop.

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}`})
      }
    }
  });
  
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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