今天学nest时,使用apifox发送请求获取数据,结果还一直报错,而且还是我从未见过的
Do not know how to serialize a BigInt at JSON.stringify (<anonymous>) at stringify,
我都是跟着人家敲的,我就纳闷了,就上网查资料 , 原来是我的PrismaClient
返回的对象中包含 BigInt
类型的字段,而 JSON.stringify
无法处理 BigInt
类型,从而导致这个错误。
以下是我的代码:
import { Controller, Get, Param } from '@nestjs/common';
import { AppService } from './app.service';
import { PrismaClient } from "@prisma/client"@Controller()
export class AppController {prisma: PrismaClient;constructor(private readonly appService: AppService) {this.prisma = new PrismaClient()}@Get(':id')async getHello(@Param('id') id: string) {const article = await this.prisma.article.findUnique({where: {id: Number(id)}});}
}
这是从数据库的article表中查找id为 1 的数据,它里面有个content的属性,其值有百多来字
解决方法:
1.直接将BigInt 转为string
import { Controller, Get, Param } from '@nestjs/common';
import { AppService } from './app.service';
import { PrismaClient } from "@prisma/client"@Controller()
export class AppController {prisma: PrismaClient;constructor(private readonly appService: AppService) {this.prisma = new PrismaClient()}@Get(':id')async getHello(@Param('id') id: string) {const article = await this.prisma.article.findUnique({where: {id: Number(id)}});if (article) {for (const key in article) {if (typeof article[key] === 'bigint') {article[key] = article[key].toString();}}}return article;}
}
2.自定义Json.stringify 方法
import { Controller, Get, Param } from '@nestjs/common';
import { AppService } from './app.service';
import { PrismaClient } from "@prisma/client"@Controller()
export class AppController {prisma: PrismaClient;constructor(private readonly appService: AppService) {this.prisma = new PrismaClient()}@Get(':id')async getHello(@Param('id') id: string) {const article = await this.prisma.article.findUnique({where: {id: Number(id)}});const customJSONStringify = (obj: any) => {return JSON.stringify(obj, (key, value) =>typeof value === 'bigint' ? value.toString() : value);};return JSON.parse(customJSONStringify(article));}
}
解决后获取到的数据:
content的值使用mock随机生成的