node.js - typescript + Express : Property 'rawBody' does not exist on type 'IncomingMessage'

标签 node.js typescript express

在我的 src/app.ts 中,我有:

import express from 'express';
import bodyParser from 'body-parser';
const app = express()

app.use(bodyParser.json({ verify: (req, res, buf) => req.rawBody = buf }))

但我收到错误“IncomingMessage”类型上不存在属性“rawBody”:

app.use(bodyParser.json({ verify: (req, res, buf) => req.rawBody = buf }))

我有一个 typings/express.d.ts,其中有:

declare namespace Express {
    export interface Request {
        rawBody: any;
    }
}

我的tsconfig.json是:

{
    "compilerOptions": {
        "outDir": "./built",
        "allowJs": true,
        "target": "es6",
        "esModuleInterop": true,
        "sourceMap": true,
        "moduleResolution": "node"
    },
    "include": [
        "./src/**/*"
    ],
    "files": [
        "typings/*"
    ]
}

那么我做错了什么?

最佳答案

这里有两个问题:

1。 tsconfig.json

tsconfig.json 中的 files 选项不支持 typings/* 等通配符,仅支持显式文件名。

您可以指定完整路径:

"files": [
    "typings/express.d.ts"
]

或者将通配符路径添加到include:

"include": [
    "./src/**/*",
    "typings/*"
]

2。类型错误

错误消息提到了 IncomingMessage 类型,但是您正在增强 Request 接口(interface)。看一下 body-parser 的类型定义(部分省略):

import * as http from 'http';

// ...

interface Options {
    inflate?: boolean;
    limit?: number | string;
    type?: string | string[] | ((req: http.IncomingMessage) => any);
    verify?(req: http.IncomingMessage, res: http.ServerResponse, buf: Buffer, encoding: string): void;
}

verify 的第一个参数的类型为 http.IncomingMessage,来自 Node.js 附带的 'http' 模块。

要增强正确的类型,您需要将 .d.ts 文件更改为:

declare module 'http' {
    interface IncomingMessage {
        rawBody: any;
    }
}

关于node.js - typescript + Express : Property 'rawBody' does not exist on type 'IncomingMessage' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58049052/

相关文章:

json - 执行正确的 MongoDB 查询(类型错误 : Converting circular structure to JSON)

node.js - 我是一个完整的新手,如何学习 Node.Js + Express + MongoDB?

javascript - Typescript/Javascript 赋值并返回单行代码

typescript - 模块导入返回空对象

javascript - 如何使用 Postman 测试 Passport.js 的基本承载策略

node.js - fs 模块函数使用的当前目录是什么?

node.js - bot-framework v4 (node.js) 中的动态提示选择

node.js - NodeJS ExpressJS PassportJS - 仅用于管理页面

node.js - RichResponse VS basicCard 顺序

javascript - Angular 5 - 从子组件输入 [(ngModel)] 绑定(bind)更改父属性