我正在使用Node和Express构建电影API。 我的过滤器函数未返回该值, 到目前为止,我的代码如下:
class MovieStore{
constructor(){
this.movieData = require('./db/database.json');
}
all(){
return this.movieData;
}
findMovie(tittle){
return this.movieData.filter(movie => movie.Tittle === tittle);
}
}
过滤器功能是否有问题?即使我从URL传递了params值,它也仅返回[]
。
这是我的json:
[
{
"Title":"Guardians of the Galaxy Vol. 2",
"Year":"2017",
"Rated":"PG-13",
"Released":"05 May 2017",
"Runtime":"136 min",
"Genre":"Action, Adventure, Comedy",
"Director":"James Gunn",
"Writer":"James Gunn"
}
]
答案 0 :(得分:0)
我的过滤器函数未返回值...仅返回[]
您的过滤器代码可以正常运行,只需要进行较小的错字修复(在下面的注释中突出显示):
/* define our test database */
const inMemoryDatabase = [
{
"Title":"Guardians of the Galaxy Vol. 2",
"Year":"2017",
"Rated":"PG-13",
"Released":"05 May 2017",
"Runtime":"136 min",
"Genre":"Action, Adventure, Comedy",
"Director":"James Gunn",
"Writer":"James Gunn"
},
{
"Title":"Pacific Rim",
"Year":"2013",
"Director":"Guillermo del Toro",
"Writer":"Travis Beacham"
}
]
/* define your class */
class MovieStore{
constructor(){
this.movieData = inMemoryDatabase
}
all(){
return this.movieData;
}
findMovie(tittle){
return this.movieData.filter(movie => movie.Title === tittle); // <- just fixed your typo here; the json database was using key "Title".
}
}
/* create instance of your MovieStore class */
const concreteMovieStore = new MovieStore()
console.log("ALL MOVIES IN STORAGE:\n", concreteMovieStore.all())
/* test filter function */
const movie = concreteMovieStore.findMovie("Guardians of the Galaxy Vol. 2")
console.log("SEARCH RESULT: ", movie)
希望这会有所帮助。干杯!
答案 1 :(得分:0)
//in .db/database.json
module.exports = [{
"Title":"Guardians of the Galaxy Vol. 2",
"Year":"2017",
"Rated":"PG-13",
"Released":"05 May 2017",
"Runtime":"136 min",
"Genre":"Action, Adventure, Comedy",
"Director":"James Gunn",
"Writer":"James Gunn"
}];
const movieData = require('./db/database.json');;
class MovieStore{
constructor(){}
all(){
return movieData;
}
findMovie(tittle){
return movieData.filter(movie => movie.Tittle.toLowerCase() === tittle.trim().toLowerCase());
}
}
尝试上面的代码,它将解决您的问题。