如何在nestjs中返回前端数据

发布时间:2021-02-22 17:04:05 作者:戴恩恩
来源:亿速云 阅读:457

这篇文章主要介绍了如何在nestjs中返回前端数据,亿速云小编觉得不错,现在分享给大家,也给大家做个参考,一起跟随亿速云小编来看看吧!

一、返回的数据格式对比

1、直接返回的数据格式

{
  "id": 1,
  "uuid": "cbbe7abc-b95e-48a0-8d24-b1ac93c45328",
  "name": "哈士奇1",
  "age": 12,
  "color": null,
  "createAt": "2019-07-25T09:13:30.000Z",
  "updateAt": "2019-07-25T09:13:30.000Z"
}

2、我们自己包装后的返回数据

{
 code: 0,
 message: "请求成功",
 data: {
  "id": 1,
  "uuid": "cbbe7abc-b95e-48a0-8d24-b1ac93c45328",
  "name": "哈士奇1",
  "age": 12,
  "color": null,
  "createAt": "2019-07-25T09:13:30.000Z",
  "updateAt": "2019-07-25T09:13:30.000Z"
 }
}

二、拦截全部的错误请求,统一返回格式

1、使用命令创建一个过滤器

nest g f filters/httpException

2、过滤器的代码

import {
 ArgumentsHost,
 Catch,
 ExceptionFilter,
 HttpException,
 HttpStatus,
 Logger,
} from '@nestjs/common';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
 catch(exception: HttpException, host: ArgumentsHost) {
  const ctx = host.switchToHttp();
  const response = ctx.getResponse();
  const request = ctx.getRequest();

  const message = exception.message.message;
  Logger.log('错误提示', message);
  const errorResponse = {
   data: {
    error: message,
   }, // 获取全部的错误信息
   message: '请求失败',
   code: 1, // 自定义code
   url: request.originalUrl, // 错误的url地址
  };
  const status =
   exception instanceof HttpException
    ? exception.getStatus()
    : HttpStatus.INTERNAL_SERVER_ERROR;
  // 设置返回的状态码、请求头、发送错误信息
  response.status(status);
  response.header('Content-Type', 'application/json; charset=utf-8');
  response.send(errorResponse);
 }
}

3、在main.ts中全局注册

...
import { HttpExceptionFilter } from './filters/http-exception.filter';

async function bootstrap() {
 ...
 // 全局注册错误的过滤器
 app.useGlobalFilters(new HttpExceptionFilter());
}
bootstrap();

4、测试,返回的错误信息

{
 "statusCode": 400,
 "error": "Bad Request",
 "data": {
  "message": [
   {
    "age": "必须的整数"
   }
  ]
 },
 "message": '请求失败',
 "code": 1,
 "url": "/api/v1/cat"
}

三、统一请求成功的返回数据

1、创建一个拦截器src/interceptor/transform.interceptor.ts

2、拦截器的代码

import {
 Injectable,
 NestInterceptor,
 CallHandler,
 ExecutionContext,
} from '@nestjs/common';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
interface Response<T> {
 data: T;
}
@Injectable()
export class TransformInterceptor<T>
 implements NestInterceptor<T, Response<T>> {
 intercept(
  context: ExecutionContext,
  next: CallHandler<T>,
 ): Observable<Response<T>> {
  return next.handle().pipe(
   map(data => {
    return {
     data,
     code: 0,
     message: '请求成功',
    };
   }),
  );
 }
}

3、全局注册

...
import { TransformInterceptor } from './interceptor/transform.interceptor';

async function bootstrap() {
 ...
 // 全局注册拦截器
 app.useGlobalInterceptors(new TransformInterceptor());
 ...
}
bootstrap();

4、测试返回数据

{
 "data": {
  "id": 1,
  "uuid": "cbbe7abc-b95e-48a0-8d24-b1ac93c45328",
  "name": "哈士奇1",
  "age": 12,
  "color": null,
  "createAt": "2019-07-25T09:13:30.000Z",
  "updateAt": "2019-07-25T09:13:30.000Z"
 },
 "code": 0,
 "message": "请求成功"
}

以上就是亿速云小编为大家收集整理的如何在nestjs中返回前端数据,如何觉得亿速云网站的内容还不错,欢迎将亿速云网站推荐给身边好友。

推荐阅读:
  1. SpringMVC 统一返回JSON格式数据到前端
  2. SharedPreferences临时存储数据 如记住密码

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

nestjs

上一篇:mysql字符串拼接换并行符

下一篇:使用matplotlib怎么绘制一个正余弦曲线图

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》