如何使用NestJS将纯文本作为请求正文传递?

时间:2018-09-11 20:24:15

标签: javascript typescript http postman nestjs

NestJS应用程序中的一种控制器方法应该以纯文本为主体,但是每当我尝试发出请求时,该参数都会作为一个空对象接收。甚至有可能吗?还是我必须创建某种DTO才能传递单个字符串?

示例:

composer install

7 个答案:

答案 0 :(得分:5)

添加@yumaa's post above

以下是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;
})

答案 1 :(得分:2)

我看到这个问题已经很老了,但是它在Google中排在第一位,所以我想在这里添加答案。

如果您不想添加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) {
  // ...

(我没有检查装饰器代码,而是在注释中写在这里)

答案 2 :(得分:0)

发布请求的语义由指示内容类型的标头确定。尝试确保请求标头的类型为“文本/纯文本”,以了解这种帮助。

https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST

答案 3 :(得分:0)

嵌套与纯文本/文本不兼容,您必须将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();

其中 选项 是根据https://www.npmjs.com/package/body-parser

创建的

答案 4 :(得分:0)

旧问题,但以上问题对我都不起作用,但以下问题确实起作用:

上述装饰器或控制器方法对我不起作用,因为始终已读取请求主体缓冲区。

我能够使用以下中间件使其工作。 (请注意,在我的情况下,我需要验证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');

答案 5 :(得分:0)

这是我在NestJS的处理程序中获取raw(text)body的观点:

  1. 使用preserveRawBodyInRequest配置应用程序,如JSDoc示例所示
  2. 在处理程序中使用RawBody装饰器来检索raw(text)body

raw-request.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,
      },
    ),
  );
}

答案 6 :(得分:0)

如果您希望避免额外的第 3 方依赖项,您还可以在此处使用 built-in 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);
}