In my src/app.ts
, I have:
import express from 'express';
import bodyParser from 'body-parser';
const app = express()
app.use(bodyParser.json({ verify: (req, res, buf) => req.rawBody = buf }))
But I get the error Property 'rawBody' does not exist on type 'IncomingMessage'
on:
app.use(bodyParser.json({ verify: (req, res, buf) => req.rawBody = buf }))
I have a typings/express.d.ts
, in which I have:
declare namespace Express {
export interface Request {
rawBody: any;
}
}
and my tsconfig.json
is:
{
"compilerOptions": {
"outDir": "./built",
"allowJs": true,
"target": "es6",
"esModuleInterop": true,
"sourceMap": true,
"moduleResolution": "node"
},
"include": [
"./src/**/*"
],
"files": [
"typings/*"
]
}
So what am I doing wrong?
The "Property does not exist on type Request" error occurs when we access a property that does not exist in the Request interface. To solve the error, extend the Request interface in a . d. ts file adding the property you intend to access on the request object.
Express body-parser is an npm module used to process data sent in an HTTP request body. It provides four express middleware for parsing JSON, Text, URL-encoded, and raw data sets over an HTTP request body. Before the target controller receives an incoming request, these middleware routines handle it.
Body-parser is the Node. js body parsing middleware. It is responsible for parsing the incoming request bodies in a middleware before you handle it. Installation of body-parser module: You can visit the link to Install body-parser module.
Express body-parser is an npm library used to process data sent through an HTTP request body. It exposes four express middlewares for parsing text, JSON, url-encoded and raw data set through an HTTP request body. These middlewares are functions that process incoming requests before they reach the target controller.
There are two issues here:
tsconfig.json
The files
option in tsconfig.json
doesn't support wildcards like typings/*
, only explicit filenames.
You can either specify the full path:
"files": [
"typings/express.d.ts"
]
Or add the wildcard path to include
:
"include": [
"./src/**/*",
"typings/*"
]
The error message mentions the type IncomingMessage
, however you are augmenting the Request
interface instead. Take a look at the type definitions for body-parser
(parts omitted):
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;
}
The first argument of verify
has the type http.IncomingMessage
from the 'http'
module that's included with Node.js.
To augment the correct type, you'll want to change your .d.ts
file to this:
declare module 'http' {
interface IncomingMessage {
rawBody: any;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With