简体   繁体   English

Express Knex req.query

[英]Express Knex req.query

express and knex are beating me a little; expressknex有点打我; I can't make this endpoint work using req.querys (response from express ), even though I made one with req.params and it was ok.我无法使用req.querys (来自express响应)使这个端点工作,即使我用req.params做了一个并且req.params


Express:表达:

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 requisition: 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);
    }
};

This might be because of the count() , but I'm not sure.这可能是因为count() ,但我不确定。 The knex part is ok; knex部分没问题; I can console.log() the result.我可以console.log()结果。 The express part showed a empty object on insomnia express部分显示insomnia的空物

失眠页面

Using 'male' as parameter it was expected to return "2" as result.使用 'male' 作为参数,预计会返回“2”作为结果。

Your sending male as a route/path parameter since you use http://localhost:3000/actor/male .由于您使用http://localhost:3000/actor/male您将male作为路由/路径参数发送。

If you want to access it as a query-param, you can leave your code as it is, but you need to change your request-url to http://localhost:3000/actor?gender=male如果你想作为查询参数访问它,你可以保留你的代码,但你需要将你的请求 URL 更改为http://localhost:3000/actor?gender=male

Note that ff you wanted to define gender as a route-parameter, you'd need to change your route-handler to app.get("/actor/:gender") and access it using req.params.gender .请注意,如果您想将gender定义为路由参数,则需要将路由处理程序更改为app.get("/actor/:gender")并使用req.params.gender访问它。

You are using path param in insomnia , not query param您在insomnia中使用path param ,而不是query param

If you want to use query params , you have to remove /male from the URL, and add query param key and value below the URL.如果要使用query params ,则必须从 URL 中删除/male ,并在 URL 下方添加query param keyvalue

You could also change the URL to locahost:3000/actor?gender=male您还可以将 URL 更改为locahost:3000/actor?gender=male

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM