我尝试为我的下一个网站制作API,但我很难在快递应用中使用相同的网址获取多个查询结果。
虚拟数据:
var data = [{
articles : [{
id : '0',
url : 'foo',
title : 'Foo',
body : 'some foo bar',
category : 'foo',
tags : [
'foo'
]
}, {
id : '1',
url : 'foo-bar',
title : 'Foo bar',
body : 'more foo bar',
category : 'foo',
tags : [
'foo', 'bar'
]
}, {
id : '2',
url : 'foo-bar-baz',
title : 'Foo bar baz',
body : 'more foo bar baz',
category : 'foo',
tags : [
'foo',
'bar',
'baz'
]
}]
}, {
users : [{
name: 'Admin'
}, {
name: 'User'
}]
}];
路由器:
// Grabs articles by categories and tags
// http://127.0.0.1:3000/api/articles/category/foo/tag/bar
router.get('/articles/category/:cat/tag/:tag', function(req, res) {
var articles = data[0].articles;
var q = articles.filter(function (article) {
return article.category === req.params.cat;
return article.tags.some(function(tagId) { return tagId === req.params.tag;});
});
res.json(q);
});
如果我请求http://127.0.0.1:3000/api/articles/category/foo/tag/bar
网址,我如何嵌套结果?现在,如果我执行此操作,则会忽略tag
个网址,只有category
个请求生效。
感谢您的帮助!
答案 0 :(得分:1)
问题在这里>>
return article.category === req.params.cat;
return article.tags.some(function(tagId) { return tagId === req.params.tag;});
第一个return
语句将停止函数内的进一步操作
所以你需要if ... else
或case
或帮助函数
答案 1 :(得分:1)
您需要重写return
语句,如下所示:
return article.category === req.params.cat &&
article.tags.some(function(tagId) {
return tagId === req.params.tag;
});
...使用&&
operator,否则你只会在第一个条件下进行测试,永远不会到达另一个语句。
如果请求属于类别&f; foo'并标记' bar':
var data =
[
{ articles:
[
{ id: '0', url: 'audrey-hepburn', title: 'Audrey Hepburn', body: 'Nothing is impossible, the word itself says \'I\'m possible\'!', category: 'foo', tags: [ 'foo' ] },
{ id: '1', url: 'walt-disney', title: 'Walt Disney', body: 'You may not realize it when it happens, but a kick in the teeth may be the best thing in the world for you.', category: 'foo', tags: [ 'foo', 'bar' ] },
{ id: '2', url: 'unknown', title: 'Unknown', body: 'Even the greatest was once a beginner. Don\'t be afraid to take that first step.', category: 'bar', tags: [ 'foo', 'bar', 'baz' ] },
{ id: '3', url: 'neale-donald-walsch', title: 'Neale Donald Walsch', body: 'You are afraid to die, and you\'re afraid to live. What a way to exist.', category: 'bar', tags: [ 'foo', 'bar', 'baz' ] }
]
},
{ users:
[
{ name: 'Admin' },
{ name: 'User' }
]
}
];
req = {params: {cat: 'foo', tag: 'bar'}};
var articles = data[0].articles;
var q = articles.filter(function (article) {
return article.category === req.params.cat &&
article.tags.some(function(tagId) {
return tagId === req.params.tag;
});
});
document.write('<pre>', JSON.stringify(q, null, 4), '</pre>');
&#13;
查看它与最后一个条目的匹配程度。