【问题标题】:How to get GET params from express with typescript in node.js?如何在 node.js 中使用 typescript 从 express 获取 GET 参数?
【发布时间】:2020-11-29 15:45:43
【问题描述】:

我正在使用 node.js + express + typescript,我想获取 GET 参数。到目前为止我有这个

app.get('/top_games', (req, res) => {
    const page = req.route.page;
    const offset = req.route.offset;
    const game_data = DAO_GAME.GetTopGuilds(100, 0);
    res.send({
        total : game_data[0],
        data : game_data[1]
    });
});

但是 eslint 抱怨

    const page = req.route.page;
    const offset = req.route.offset;

Unsafe assignment of an any value.eslint@typescript-eslint/no-unsafe-assignment
Unsafe member access .page on an any value.eslint@typescript-eslint/no-unsafe-member-access

我该如何解决这个问题?

【问题讨论】:

  • req.params 给你什么? app.get('/user/:id', function (req, res) { res.send('user ' + req.params.id) })
  • req.paramsget me {},数据在req.query

标签: node.js typescript express eslint


【解决方案1】:

修好了,我不得不做

const page = parseInt(req.query.page as string, 10);
const page_size = parseInt(req.query.page_size as string, 10);

【讨论】:

    【解决方案2】:

    截至@types/express@4.17.2Request type uses generics。我们可以使用它来自己键入解析后的查询参数:

    import { Request } from 'express';
    
    type QueryParams = {
        page: string;
        page_size: string;
    };
    
    app.get('/top_games', (req: Request<{}, {}, {}, QueryParams>, res) => {
        const page = parseInt(req.route.page, 10);
        const offset = parseInt(req.route.offset, 10);
    
        // ...
    });
    

    【讨论】:

    • 感谢您回答这个问题,我最近几天才试图弄清楚这个问题,这正是我想要的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-06
    • 1970-01-01
    • 1970-01-01
    • 2022-12-03
    • 1970-01-01
    • 2017-05-09
    相关资源
    最近更新 更多