在返回中间件的快速路由中调用函数

编程入门 行业动态 更新时间:2024-10-05 11:24:11

在返回中间件的快速<a href=https://www.elefans.com/category/jswz/34/1771390.html style=路由中调用函数"/>

在返回中间件的快速路由中调用函数

我正在创建一个自定义函数来处理 API 请求验证。它是这样完成的:

export function validateBody(schema: string): (req: ExpressRequest, res: ExpressResponse, next: ExpressNextFunction) => void {
    return function (req: ExpressRequest, res: ExpressResponse, next: ExpressNextFunction): void | ExpressResponse {
        // Some operation
        next();
    }
}

它在 api 路由中用作返回中间件的函数调用

router.route('/api/users/currentuser').get(validateBody('signIn'), (req: ExpressRequest, res: ExpressResponse, next: ExpressNextFunction) => {

我收到以下 lint 错误

No overload matches this call.
  The last overload gave the following error.
    Argument of type '(req: ExpressRequest, res: ExpressResponse, next: ExpressNextFunction) => void' is not assignable to parameter of type 'RequestHandlerParams<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.
      Type '(req: ExpressRequest, res: ExpressResponse, next: ExpressNextFunction) => void' is not assignable to type 'RequestHandler<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.
        Types of parameters 'req' and 'req' are incompatible.
          Property 'value' is missing in type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>' but required in type 'ExpressRequest'.ts(2769)
types.ts(4, 5): 'value' is declared here.
index.d.ts(222, 5): The last overload is declared here.

它期待我尝试使用的“RequestHandleParam”类型,但它开始在“validateBody”函数定义中抛出错误。非常感谢任何解决方案或解决方法。

Ps: 使用 javascript 而不是 typescript 可以按预期工作。

回答如下:

使用起来更简单的接口是RequestHandler。它隐式地键入了所有请求处理程序函数参数,这减少了很多样板文件

import { RequestHandler } from "express";

const validateBody =
  (schema: string): RequestHandler =>
  (_req, _res, next) => {
    next();
  };

更多推荐

在返回中间件的快速路由中调用函数

本文发布于:2024-05-30 07:37:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1770262.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路由   函数   中间件   快速

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!