javascript - 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 文件中检索对象我该如何解决这个问题?
解决方案
您收到的错误
_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}`})
}
}
});
});
推荐阅读
- python - 使用 DJANGO 执行 runserver 时 psycopg2 出错
- docker - Nginx 与 docker:反向代理不起作用
- listview - 如何检测 Listview 中的水平滚动运动?(适用于 VS2015 C++/CLI)
- vbscript - VBScript 程序错误地识别它的 PID?
- dask - 从集群上的 h5 文件加载非常猪油数据时出现内存错误
- firebase - user_engagement 事件背后的周期性是什么?
- r - R ggplot2 hexbin 绘图图形错误?
- mysql - 如何在 Debian 的一个命令行中在 MariaDB 中创建新用户
- haskell - 绑定到记录实例的记忆函数的 Haskell 生命周期
- c++ - 为什么指针在 C++ 中丢弃值?