我希望实现一项功能,使用户能够按位置过滤/获取业务。这是我的逻辑:
指定的位置或带有相应状态代码的错误消息。
This is the mock database:
const businesses = [
{
id: 1,
businessName: 'Kulikuli and Sons Limited',
description: 'We take you to heaven and back',
email: 'kososhi@gmail.com',
location: 'Kaduna',
category: 'Hospitality',
phoneNumber: '07033288342'
},
{
id: 2,
businessName: 'Rochas Limited',
description: 'We satisfy all your maintenance',
email: 'rochas2u@gmail',
location: 'Lagos',
category: 'Repairs and Maintenance',
phoneNumber: '07033288341'
},
{
id: 3,
businessName: 'Lekoto Travels',
description: 'Travel with us and you won\'t regret it',
email: 'lekotoboss@gmail.com',
location: 'Kaduna',
category: 'Travels and Tours',
phoneNumber: '07033288344'
},
];
This is the method to control the route: GET /businesses?location=<location>
static filterByLocation(req, res) {
const filteredLocation = [];
for (let i = 0; i < businesses.length; i += 1) {
if (typeof req.query.location !== 'undefined') {
businesses.filter((business) => {
if (business.location === req.query.location) {
filteredLocation.push(business);
}
});
}
return res.status(200).send({
status: 'Success',
location: filteredLocation
});
}
return res.status(404).send({
status: 'Fail',
message: 'Location not found'
});
}
However, the code isn't working as expected. Where am I getting it wrong?
答案 0 :(得分:0)
试试这个,Filter函数返回过滤结果不需要根据条件推入数组,而res.send不返回JSON所以你必须使用res.json()或res.send(JSON.stringify(json) )。你正在返回内部for循环的响应,这将无效。
static filterByLocation(req, res) {
const filteredLocation = businesses.filter((business) => {
return business.location === req.query.location;
});
if (filteredLocation.length !== 0)
return res.status(200).json({
status: 'Success',
location: filteredLocation
});
return res.status(404).json({
status: 'Fail',
message: 'Location not found'
});
}