My client expects all successful status codes to equal 200. However NestJS uses 201 by default for all POST methods. How do I disable 201 for POSTs application wide? Not for one method but for the entire app.
You should specify status codes for every controller
According official docs https://docs.nestjs.com/controllers#status-code
Furthermore, the response's status code is always 200 by default, except for POST requests which use 201. We can easily change this behavior by adding the @HttpCode(...) decorator at a handler-level (see Status codes).
@Post()
@HttpCode(200)
create() {
return 'This action adds data';
}
Also nestjs has another way which depends on library (express/fastify):
We can use the library-specific (e.g., Express) response object, which can be injected using the @Res() decorator in the method handler signature (e.g., findAll(@Res() response)). With this approach, you have the ability (and the responsibility), to use the native response handling methods exposed by that object. For example, with Express, you can construct responses using code like response.status(200).send()
But if it's possible I recommend to use Reponse.ok to indetify success Response on the client side
Make an interceptor. But tbh, what's so bad about 201?
import { CallHandler, ExecutionContext, Injectable, HttpStatus } from '@nestjs/common';
import { map } from 'rxjs/operators';
@Injectable()
export class PostStatusInterceptor {
intercept(context: ExecutionContext, next: CallHandler) {
const ctx = context.switchToHttp();
const req = ctx.getRequest();
const res = ctx.getResponse();
return next.handle().pipe(
map(value => {
if (req.method === 'POST') {
if (res.statusCode === HttpStatus.CREATED) {
res.status(HttpStatus.OK);
}
}
return value;
}),
);
}
}
https://docs.nestjs.com/interceptors
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With