[英]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.