nestjs返回给前端数据格式的封装实现
⼀般开发过程中不不会根据httpcode来判断接⼝请求成功与失败的,⽽是会根据请求返回的数据,⾥⾯加上code字段⼀、返回的数据格式对⽐
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,
js arguments"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 = Response();
const request = Request();
const message = ssage;
Logger.log('错误提⽰', message);
const errorResponse = {
data: {
error: message,
}, // 获取全部的错误信息
message: '请求失败',
code: 1, // ⾃定义code
url: iginalUrl, // 错误的url地址
};
const status =
exception instanceof HttpException
: 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返回给前端数据格式的封装实现的⽂章就介绍到这了,更多相关nestjs返回给前端数据格式内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。