[英]How do I pass plain text as my request body using NestJS?
我的 NestJS 應用程序中的控制器方法之一應該將純文本作為其主體,但是每當我嘗試發出請求時,參數都會作為空對象接收。 這甚至是可能的,還是我將不得不創建某種 DTO 來傳遞該單個字符串?
例子:
@Post()
myFunction(@Body() id: string) {
// do something here
}
我看到這個問題很老了,但它在谷歌中列在第一位,所以我想在這里添加答案。
如果您不想添加body-parser
中間件(例如,您只希望在單個控制器方法中使用純文本),您可以使用raw-body
(它已經存在於您的 node_modules 中),如下所示:
import * as rawbody from 'raw-body';
import { Controller, Post, Body, Req } from '@nestjs/common';
@Controller('/')
export class IndexController {
@Post()
async index(@Body() data, @Req() req) {
// we have to check req.readable because of raw-body issue #57
// https://github.com/stream-utils/raw-body/issues/57
if (req.readable) {
// body is ignored by NestJS -> get raw body from request
const raw = await rawbody(req);
const text = raw.toString().trim();
console.log('body:', text);
} else {
// body is parsed by NestJS
console.log('data:', data);
}
// ...
}
}
您還可以創建新的參數裝飾器
import * as rawbody from 'raw-body';
import { createParamDecorator, HttpException, HttpStatus } from '@nestjs/common';
export const PlainBody = createParamDecorator(async (data, req) => {
if (req.readable) {
return (await rawbody(req)).toString().trim();
}
throw new HttpException('Body aint text/plain', HttpStatus.INTERNAL_SERVER_ERROR);
});
並像使用它一樣
@Post()
async index(@PlainBody() text: string) {
// ...
(我沒有檢查裝飾器代碼,就在評論中寫在這里)
這是 NestJS v7.0.8 的工作裝飾器:
import { createParamDecorator, ExecutionContext, BadRequestException } from '@nestjs/common';
import * as rawBody from "raw-body";
export const PlainBody = createParamDecorator(async (_, context: ExecutionContext) => {
const req = context.switchToHttp().getRequest<import("express").Request>();
if (!req.readable) { throw new BadRequestException("Invalid body"); }
const body = (await rawBody(req)).toString("utf8").trim();
return body;
})
post 請求的語義由指示內容類型的標頭確定。 嘗試確保請求標頭的類型為“text/plain”,看看這是否有幫助。
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST
Nest 與純文本/文本不兼容,您必須將 bodyparser 傳遞給您的 express 應用程序。 嘗試這樣的事情:
import * as bodyParser from 'body-parser';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.use(bodyparser({ ...options })) // for plain/text bodies
await app.listen(3000)
}
bootstrap();
老問題,但以上都沒有為我工作,但以下做了:
上述裝飾器或控制器方法方法對我不起作用,因為請求正文緩沖區始終已被讀取。
我能夠使用以下中間件讓它工作。 (請注意,在我的情況下,我需要驗證 Xero webhook,因此該示例是針對此的)
cache-raw-body-on-request.ts:
import { json } from 'body-parser';
import * as cloneBuffer from 'clone-buffer';
export const cachedRawBodyRequestKey = 'rawBodyBuffer';
/**
* Clones the request buffer and stores it on the request object for reading later
*/
export const cacheRawBodyOnRequest = json({
verify: (req: any, res, buf, encoding) => {
// only clone the buffer if we're receiving a Xero webhook request
if (req.headers['x-xero-signature'] && Buffer.isBuffer(buf)) {
req[cachedRawBodyRequestKey] = cloneBuffer(buf);
}
return true;
},
});
main.ts:
app.use(cacheRawBodyOnRequest);
控制器:
const textBody = req[cachedRawBodyRequestKey].toString('utf-8');
這是我在 NestJS 的處理程序中獲取原始(文本)正文的看法:
preserveRawBodyInRequest
配置應用程序,如JSDoc 示例中所示RawBody
裝飾器來檢索原始(文本)正文原始請求.decorator.ts:
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { NestExpressApplication } from "@nestjs/platform-express";
import { json, urlencoded } from "express";
import type { Request } from "express";
import type http from "http";
export const HTTP_REQUEST_RAW_BODY = "rawBody";
/**
* make sure you configure the nest app with <code>preserveRawBodyInRequest</code>
* @example
* webhook(@RawBody() rawBody: string): Record<string, unknown> {
* return { received: true };
* }
* @see preserveRawBodyInRequest
*/
export const RawBody = createParamDecorator(
async (data: unknown, context: ExecutionContext) => {
const request = context
.switchToHttp()
.getRequest<Request>()
;
if (!(HTTP_REQUEST_RAW_BODY in request)) {
throw new Error(
`RawBody not preserved for request in handler: ${context.getClass().name}::${context.getHandler().name}`,
);
}
const rawBody = request[HTTP_REQUEST_RAW_BODY];
return rawBody;
},
);
/**
* @example
* const app = await NestFactory.create<NestExpressApplication>(
* AppModule,
* {
* bodyParser: false, // it is prerequisite to disable nest's default body parser
* },
* );
* preserveRawBodyInRequest(
* app,
* "signature-header",
* );
* @param app
* @param ifRequestContainsHeader
*/
export function preserveRawBodyInRequest(
app: NestExpressApplication,
...ifRequestContainsHeader: string[]
): void {
const rawBodyBuffer = (
req: http.IncomingMessage,
res: http.ServerResponse,
buf: Buffer,
): void => {
if (
buf?.length
&& (ifRequestContainsHeader.length === 0
|| ifRequestContainsHeader.some(filterHeader => req.headers[filterHeader])
)
) {
req[HTTP_REQUEST_RAW_BODY] = buf.toString("utf8");
}
};
app.use(
urlencoded(
{
verify: rawBodyBuffer,
extended: true,
},
),
);
app.use(
json(
{
verify: rawBodyBuffer,
},
),
);
}
如果您希望避免額外的 3rd 方依賴項,您還可以在此處使用內置的nodejs 方法:
function readPost(req: IncomingMessage) {
return new Promise<string>((resolve, reject) => {
let body = '';
req.on('data', (data: string) => (body += data));
req.on('error', (error: unknown) => reject(error));
req.on('end', () => resolve(body));
});
}
用法:
import { Post, Req } from '@nestjs/common';
import { IncomingMessage } from 'http';
...
@Post()
myFunction(@Req() req: IncomingMessage) {
const bodyStr = await readPost(req);
console.log('request body:', bodyStr);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.