I was working with this API and everything was fine until I've tried POST method.
Now what happens is, when I try to send data from postman, NodeJS app crashes, displaying this error: HTTPError: Response code 400 (Bad Request) and pointing that error is called in the catch part.
So thing is, when I directly send post request to the API directly (not with my localhost server) it returns 400: Bad request with message that data is not correct. Now everything is okay when I send it directly, but when I try to call the API with my localhost it throws that error.
The error is throw from the call: got.post(...) which uses this library:
https://www.npmjs.com/package/got
Is it possible to make that call and get the 400 response without getting an error raised from the call?
methods.ts
export const addReservation = async (postData: object) => {
const url = API_URL + '/reservation';
try {
const response = await got.post(url, {
json: { ...postData },
responseType: 'json',
});
console.log(response.statusCode); //no success, jumps to the catch block
return response.body;
} catch (error) {
throw new Error(error);
}
};
reservation.ts
export const reservationHandler = async (req: Request, res: Response) => {
let postData = req.body;
let response = await addReservation(postData);
return res.status(201).json(response); //if all is OK it will return 201, but if not 400
};
So I've tried catching the status code in addReservation but no success. I was having idea by handling cases of status codes 400 or 201, but only proceeds with try block if the status is 201, but if it is 400, it crashes the app.
got.post(...). I'm not familiar with that library, you should provide more context about it in the question.