我尝试为我的下一个网站制作 API,但在 Express 应用程序中无法使用相同的 url 获取多个查询结果。
虚拟数据:
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
url 将被忽略,只有 category
请求有效。
感谢您的帮助!
最佳答案
您需要重写您的 return
语句,如下所示:
return article.category === req.params.cat &&
article.tags.some(function(tagId) {
return tagId === req.params.tag;
});
...使用&&
operator ,否则您将仅测试第一个条件,而永远不会达到其他语句。
这是请求针对类别“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>');
查看它与最后一个条目的匹配情况。
关于Javascript:具有多个查询参数的嵌套 JSON api 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35379604/