这次express和knex有点打我,不能使用req.querys(来自express的响应)使这个endpoint工作,我用req.params做了一个,它还可以。
快车
app.get(`/actor`, async (req: Request, res: Response) => {
try {
// const { gender } = req.query;
const count = await getActorsByGender(req.query.gender as string);
console.log({ count });
res.status(200).send({ quantity: count, });
} catch (error) {
res.status(200).send({ message: error.sqlMessage || error.message });
}
});
Knex申请
const getActorsByGender = async (gender: string): Promise<any> => {
try {
const result = await connection.raw(`
SELECT COUNT(*) as count FROM Actor
WHERE gender = "${gender}"
`);
// console.log(`Temos: ${result[0][0].count} ocorrências`);
return result;
} catch (error) {
console.log(error);
}
};
不知道这是不是因为count(),nex部分是ok的,我可以console.log结果。所述表达部分显示了一个关于失眠空物体
如果使用“male”作为参数,则预期返回“2”作为结果。
您在失眠中使用的是路径参数,而不是查询参数
如果要使用查询参数,您必须从url中删除/male
,并在url下方添加查询参数键和值
也可以将url更改为locahost:3000/actor?gender=male
因为您使用http://localhost:3000/actor/male
,所以将发送male
作为路由参数。
如果希望将其作为查询参数访问,则可以保持代码原样,但需要将request-url更改为http://localhost:3000/actor?gender=male
如果要将gender
定义为路由参数,则需要将路由处理程序更改为app.get(“/actor/:gender”)
,并使用req.params.gender
访问它。