I am beginner in NestJS and I would like to ask question on how to use Axios in NestJs. But the problem is I keep getting error TypeError: Converting circular structure to JSON
I have created an API POST http://localhost:3000/api/create in NestJS and my raw request
Raw input
{
"id":1,
"date":"2022-06-28",
"roster":[
{
"startDate":"2022-06-27",
"weekDay":1,
"session":1,
"sTime":"08:00:00",
"eTime":"10:00:00"
}
]
}
My goal is in create.service.ts file, I want pass the value that I receive in postman and add all values into new API link https://create.com/api/index.php?id=&date=&roster=[].
Expected output : https://create.com/api/index.php?id=1&date=2022-06-27&roster=[{"startDate":"2022-06-27","weekDay":1,"session":1,"sTime":"08:00:00","eTime":"10:00:00"}]
But I receive an error TypeError: Converting circular structure to JSON when I submit my post request
create.service.ts
import { HttpException, Injectable } from '@nestjs/common';
import axios from 'axios';
import { CreateValidator } from './create.validator';
@Injectable()
export class CreateService {
constructor() { }
async create(query: CreateValidator) {
return axios.post(`https://create.com/api/index.php?`, null, { params: query })
.then()
.catch(err => {
throw new HttpException(err.response?.data ?? err.response?.statusText ?? 'Unexpected error.', err.response?.status ?? 400);
});
}
}
create.controller.ts
import { Post, Body } from '@nestjs/common';
import { ApiConsumes, ApiTags } from '@nestjs/swagger';
import { BaseController } from '../base/base.controller';
import { CreateService } from './create.service';
import { CreateValidator } from './create.validator';
@ApiTags('New : Create ')
export class CreateController extends BaseController {
constructor(
private readonly createService: CreateService,
) {
super();
}
@Post('api/create')
@ApiConsumes('application/x-www-form-urlencoded')
async create(@Body() body: CreateValidator) {
const result = await this.createService.create(body);
return {result,};
}
}
create.validator.ts
import { ApiProperty } from '@nestjs/swagger';
import { Transform } from 'class-transformer';
import { IsNotEmpty, isString } from 'class-validator';
export class CreateValidator {
@ApiProperty({type: Number,required: true,})
id: number;
@ApiProperty({type: String,required: true,})
date: Date;
@ApiProperty({type: [Object],})
@Transform((input) => isString(input.value) ? JSON.parse(input.value) : input.value)
@IsNotEmpty({ message: 'IsNotEmpty' })
roster: Array<{
startDate: Date;
weekDay: number;
s_time: string;
e_time: string;
}>;
}
My current coding as below