如何在这些路线上使用可选查询过滤器,例如“/ employees?department = 4”并返回部门编号为4的数据
app.get("/employees", (req, res) => {
dataService.getAllEmployees().then(function(data) {
res.json(data);
}).catch(function(err) {
var error = { "message": err };
res.json(error);
});
我已经在dataService模块中有函数,它返回id为
的部门的承诺function getEmployeesByDepartment(department) {
return new Promise((resolve, reject) => {
try {
employees.forEach((element) => {
if (element.department == department) {
resolve(element);
}
});
} catch (error) {
reject("no data returned");
}
});
}
答案 0 :(得分:1)
您可以使用req.query
获取查询字符串数据并将部门传递给getEmployeesByDepartment
函数。
app.get("/employees", (req, res) => {
var department = req.query.department || "";
if(department){
getEmployeesByDepartment(department).then(data => res.json(data));
}
else{
dataService.getAllEmployees().then((data) => {
res.json(data);
}).catch((err) => {
var error = { "message": err };
res.json(error);
}
);
答案 1 :(得分:0)
您可以使用req.query
对象访问查询参数。
在您的情况下,代码将类似于:
if (req.query.department) {
return getEmployeesByDepartment(req.query.department).then(
data => res.json(data)
);
} else {
return dataService.getAllEmployees().then(
data => res.json(data)
);
}