node.js - TypeScript + Express:“IncomingMessage”类型上不存在属性“rawBody”
问题描述
在我的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 }))
但我得到了错误Property 'rawBody' does not exist on type 'IncomingMessage'
:
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
中的files
选项tsconfig.json
不支持通配符typings/*
,仅支持显式文件名。
您可以指定完整路径:
"files": [
"typings/express.d.ts"
]
或将通配符路径添加到include
:
"include": [
"./src/**/*",
"typings/*"
]
2.错误类型
错误消息提到了 type IncomingMessage
,但是您正在扩充Request
界面。看一下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;
}
的第一个参数具有 Node.js 中包含的模块verify
的类型。http.IncomingMessage
'http'
要增加正确的类型,您需要将.d.ts
文件更改为:
declare module 'http' {
interface IncomingMessage {
rawBody: any;
}
}
推荐阅读
- google-analytics - 为什么我们的页面级唯一事件低于相同页面的唯一页面浏览量?
- xml - xml 模式 - 具有一个元素的替换组出现不超过一次
- java - 动态生成一个 json 对象
- c# - AmbiguousMatchException:操作请求不明确
- postgresql - 插入到只有一个元素的自定义类型的表列
- ms-access - 我的语法工作而不是编写完整的控制地址。为什么?
- windows - 如何从 DLL 文件中获取一些基本信息?
- c++ - c++ 中没有 timeout_exception 吗?
- sql-server - 运行总计和运行减法
- kubernetes - 如何从同一台计算机访问在 minikube 中运行的 kubernete 服务