nestjs返回給前端數(shù)據(jù)格式的封裝實(shí)現(xiàn)
一般開(kāi)發(fā)過(guò)程中不不會(huì)根據(jù)httpcode來(lái)判斷接口請(qǐng)求成功與失敗的,而是會(huì)根據(jù)請(qǐng)求返回的數(shù)據(jù),里面加上code字段
一、返回的數(shù)據(jù)格式對(duì)比
1、直接返回的數(shù)據(jù)格式
{
"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、我們自己包裝后的返回?cái)?shù)據(jù)
{
code: 0,
message: "請(qǐng)求成功",
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"
}
}
二、攔截全部的錯(cuò)誤請(qǐng)求,統(tǒng)一返回格式
1、使用命令創(chuàng)建一個(gè)過(guò)濾器
nest g f filters/httpException
2、過(guò)濾器的代碼
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('錯(cuò)誤提示', message);
const errorResponse = {
data: {
error: message,
}, // 獲取全部的錯(cuò)誤信息
message: '請(qǐng)求失敗',
code: 1, // 自定義code
url: request.originalUrl, // 錯(cuò)誤的url地址
};
const status =
exception instanceof HttpException
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;
// 設(shè)置返回的狀態(tài)碼、請(qǐng)求頭、發(fā)送錯(cuò)誤信息
response.status(status);
response.header('Content-Type', 'application/json; charset=utf-8');
response.send(errorResponse);
}
}
3、在main.ts中全局注冊(cè)
...
import { HttpExceptionFilter } from './filters/http-exception.filter';
async function bootstrap() {
...
// 全局注冊(cè)錯(cuò)誤的過(guò)濾器
app.useGlobalFilters(new HttpExceptionFilter());
}
bootstrap();
4、測(cè)試,返回的錯(cuò)誤信息
{
"statusCode": 400,
"error": "Bad Request",
"data": {
"message": [
{
"age": "必須的整數(shù)"
}
]
},
"message": '請(qǐng)求失敗',
"code": 1,
"url": "/api/v1/cat"
}
三、統(tǒng)一請(qǐng)求成功的返回?cái)?shù)據(jù)
1、創(chuàng)建一個(gè)攔截器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: '請(qǐng)求成功',
};
}),
);
}
}
3、全局注冊(cè)
...
import { TransformInterceptor } from './interceptor/transform.interceptor';
async function bootstrap() {
...
// 全局注冊(cè)攔截器
app.useGlobalInterceptors(new TransformInterceptor());
...
}
bootstrap();
4、測(cè)試返回?cái)?shù)據(jù)
{
"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": "請(qǐng)求成功"
}
到此這篇關(guān)于nestjs返回給前端數(shù)據(jù)格式的封裝實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)nestjs返回給前端數(shù)據(jù)格式內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
微信小程序 數(shù)據(jù)緩存實(shí)現(xiàn)方法詳解
這篇文章主要介紹了微信小程序 數(shù)據(jù)緩存實(shí)現(xiàn)方法詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08
javascript 中模板方法單例的實(shí)現(xiàn)方法
這篇文章主要介紹了javascript 中模板方法單例的實(shí)現(xiàn)方法的相關(guān)資料,希望通過(guò)本文能幫助到大家,需要的朋友可以參考下2017-10-10
在Monaco Editor中實(shí)現(xiàn)斷點(diǎn)設(shè)置的方法詳解
Monaco Editor 是 vscode 等產(chǎn)品使用的代碼編輯器,功能強(qiáng)大(且復(fù)雜),由微軟維護(hù),本文在 React + TypeScript(Vite)框架下使用 @monaco-editor/react 并介紹開(kāi)發(fā)斷點(diǎn)顯示時(shí)踩到的坑,文中有詳細(xì)的代碼示例供大家參考,需要的朋友可以參考下2024-04-04
js實(shí)現(xiàn)通過(guò)開(kāi)始結(jié)束控制的計(jì)時(shí)器
這篇文章主要為大家詳細(xì)介紹了js實(shí)現(xiàn)通過(guò)開(kāi)始結(jié)束控制的計(jì)時(shí)器,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-02-02
JavaScript中使用stopPropagation函數(shù)停止事件傳播例子
這篇文章主要介紹了JavaScript中使用stopPropagation函數(shù)停止事件傳播例子,即阻止事件冒泡的一個(gè)方法,需要的朋友可以參考下2014-08-08

