Node.js + Express + TypeScript:req.query 类型
在使用 Node 和 Express.js 时,可能存在需要访问req.query的情况,这是一个包含路由中每个查询字符串参数的属性的对象。例如,给定这样的路线:
http://localhost:3000?foo=abc&bar=def&something=123
然后req.query将如下所示:
{ foo: 'abc', bar: 'def', something: '123' }
如果您使用TypeScript编写代码,您可能想知道req.query 的 正确类型是什么?这个问题有不止一个解决方案。****
解决方案 1
Request接口(可以从express导入)是一个接受附加定义的泛型:
interface Request<
P = core.ParamsDictionary,
ResBody = any,
ReqBody = any,
ReqQuery = core.Query,
Locals extends Record<string, any> = Record<string, any>
> extends core.Request<P, ResBody, ReqBody, ReqQuery, Locals> {}
因此,我们可以这样做:
import { Request, Response, NextFunction } from 'express';
// interfaces
interface ReqParams {
/* Add something as needed */
}
interface ReqBody {
/* Add something as needed */
}
interface Resbody {
/* Add something as needed */
}
interface ReqQuery {
foo: string;
bar: string;
something?: string;
}
// controller
export const getThings = (
req: Request<ReqParams, ReqBody, Resbody, ReqQuery>,
res: Response,
next: NextFunction
) => {
const { foo, bar, something } = req.query;
console.log(foo, bar, something);
res.status(200).json({ message: 'Welcome to KindaCode.com!' });
};
解决方案 2
您还可以像这样使用类型转换:
import { Request, Response, NextFunction } from 'express';
// controller
export const getThings = (req: Request, res: Response, next: NextFunction) => {
const foo: string = req.query.foo as string;
const bar:string = req.query.bar as string;
const something: string = req.query.something as string;
console.log(foo, bar, something);
res.status(200).json({ message: 'Welcome to KindaCode.com!' });
};
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。