Reputation: 2292
I have a NestJS route which sends back in response, a JSON not well formatted (like minified), I want to make this JSON easier to read, like a JSON prettier or JSON formatted, Do someone knows how to do it in NestJS ? I accept answers for other NodeJS frameworks like Express, maybe it will work in NestJS too...
Upvotes: 3
Views: 5534
Reputation: 977
string
on your controllerContent-Type: application/json
response headerJSON.stringify
to format your object with whitespaceExample controller code:
import { Controller, Get, Header } from '@nestjs/common';
@Controller('diagnostics')
export class DiagnosticsController {
@Get()
@Header('Content-Type', 'application/json')
findAll(): string {
const statusCode = 200;
const statusText = 'OK';
const info = {
self: 'NestJS Diagnostics Report',
status: {
statusCode,
statusText,
},
};
return JSON.stringify(info, null, 2);
}
}
Upvotes: 2
Reputation: 364
It works for me:
// src/main.ts
async function bootstrap() {
const app = await NestFactory.create(AppModule);
if (process.env.NODE_ENV !== 'production') {
app.getHttpAdapter().getInstance().set('json spaces', 2);
}
await app.listen(process.env.PORT);
}
Upvotes: 4
Reputation: 990
While you shouldn't do it in prod as mentioned above, there's number of cases where it makes a lot of sense (e.g. in dev env). You can achieve this in a bit hacky way:
express
instance inside nest through breaking abstraction. It's not exposed on INest
interface, so you'll need to cast it to any
type to bypass Typescript checkexpress
property "json spaces"
, which will set formatting for all JSON responses over the appconst app = await NestFactory.create(AppModule);
if (process.env.NODE_ENV === 'development') {
(app as any).httpAdapter.instance.set('json spaces', 2);
}
await app.listen(3000);
Upvotes: 1
Reputation: 19
You should try https://www.postman.com or https://insomnia.rest/. It can save you a lot of time when it comes to testing an API.
Upvotes: 0
Reputation: 70211
Prettifying the JSON response should be the responsibility of the client, not the server. Otherwise you could be sending a lot of white space which will bloat the response size and could lead to a crash due to having a response too large. If you are using something like Postman, it should be easy to prettify it, I think Postman might do it by default. If you are looking at the response in some web browser, you could use JSON.parse()
on the response and it should make the response an actual JSON which console.log()
would then print in a pretty way.
Upvotes: 3