当我沿着路线:“ / gallery”时,我从文件“ ./posts.json”中获取所有项目,并将它们显示在屏幕上。但是当我转向路线:'/ gallery /:id'时,我想通过其id
收到一件物品。
但是我得到一个错误:const pictureId = this.formatePicture.findIndex(p => p.id == parseInt(id)); TypeError: this.formatePicture.findIndex is not a function.
我尝试用for in
做data
,但是循环之后没有对象属性。
告诉我我做错了什么以及如何解决此问题,以便我在转到“ / gallery /:id”路线时通过id
获得商品 < / p>
app.js:
const express = require('express');
const Database = require('./db');
const app = express();
const port = 3000;
const db = new Database();
app.use(express.json());
app.get('/gallery', (req, res) => {
if (req.query.id) {
const picture = db.read(req.query.id);
picture.then(data => {
res.send(data);
})
} else {
const pictures = db.read();
pictures.then(data => {
res.send(data);
})
}
});
app.get('/gallery/:id', (req, res) => {
const picture = db.read(req.params.id);
if (!picture) {
res.status(404);
res.send();
} else {
picture.then(data => {
res.send(data);
})
}
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
});
db.js:
const fs = require('fs');
class Database {
constructor() {
this.formatePicture = [];
}
read (id) {
return new Promise((resolve, reject) => {
fs.readFile('./posts.json', 'utf-8', (err, data) => {
if (err) {
reject(err)
}else if(id) {
this.formatePicture = JSON.parse(data);
const pictureId = this.formatePicture.findIndex(p => p.id == parseInt(id));
resolve(pictureId)
}
else {
resolve(data)
}
})
})
}
}
module.exports = Database;
posts.json:
{
"posts": [
{
"id": 1,
"date": "2018-10-22T14:10:37.578Z",
"title": "accusamus beatae ad facilis cum similique qui sunt",
"url": "https://i.pinimg.com/originals/90/39/16/903916b9f0db6992f1a4b66ae3129fbe.jpg"
},
{
"id": 2,
"date": "2018-10-22T14:10:37.578Z",
"title": "reprehenderit est deserunt velit ipsam",
"url": "https://vignette.wikia.nocookie.net/okup/images/d/da/C683c20a5b0ae062b2325653f2fd3bdf.jpg/revision/latest?cb=20170131193210&path-prefix=da"
}
]
}
答案 0 :(得分:1)
解析的数据是一个对象,您需要定位的数组在字段posts
this.formatePicture.posts.findIndex(...)
另一种无需修改数据库代码即可实现此目的的方法是更改posts.json
中的结构,使其看起来像这样
[
{
"id": 1,
"date": "2018-10-22T14:10:37.578Z",
"title": "accusamus beatae ad facilis cum similique qui sunt",
"url": "https://i.pinimg.com/originals/90/39/16/903916b9f0db6992f1a4b66ae3129fbe.jpg"
},
{
"id": 2,
"date": "2018-10-22T14:10:37.578Z",
"title": "reprehenderit est deserunt velit ipsam",
"url": "https://vignette.wikia.nocookie.net/okup/images/d/da/C683c20a5b0ae062b2325653f2fd3bdf.jpg/revision/latest?cb=20170131193210&path-prefix=da"
}
]
您可能想使用find
而不是findIndex
,因为pictureId
是包含您共享的初始代码的索引
看起来可能是这样
const picture = this.formatePicture.find(p => p.id == parseInt(id));
// checking if we found an entry first
if (picture) {
resolve(picture.id);
} else {
reject(/* some error about resource not being found */)
}