簡體   English   中英

如何在 node.js 中使用 typescript 從快遞中獲取 GET 參數?

[英]How to get GET params from express with typescript in node.js?

我正在使用 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

我怎樣才能解決這個問題?

修好了,我必須做

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

@types/express@4.17.2開始, Request類型使用 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);

    // ...
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM