我不知道如何解释这个,但我正在尝试创建一个处理应用程序路由的函数。我想传入一个将由请求正文中的字段填充的对象。下面的代码给我一个错误req未定义。这是一个简化版本:
function getAction(data)
{
app.get(data.path, (req, res) => {
getPerson(data.model, (err, person) => {
return res.json(person);
});
});
}
getAction({
path: "/getCustomer",
model: {
name: req.query.name,
address: req.query.address
}
});
getAction({
path: "/getFriend",
model: {
name: req.query.name,
sport: req.query.sport
}
});
我想要实现的是调用
http://host//getCustomer?name=bob&address=home
将调用函数getPerson(" bob"," home")
http://host//getFriend?name=bob&sport=hockey
将调用函数getPerson(" bob"," hockey")
答案 0 :(得分:0)
好吧,req
未在您传递给getAction
的对象文字中定义。传递函数:
function getAction(path, getModel) {
app.get(data.path, (req, res, next) => {
getPerson(getModel(req), (err, person) => {
if (err) return next(err);
res.json(person);
});
});
}
getAction("/getCustomer", req => ({
name: req.query.name,
address: req.query.address
}));
getAction("/getFriend", req => ({
name: req.query.name,
sport: req.query.sport
}));