I’m developing a NestJS application where I need to obtain a JWT token by making a POST request. I’m utilizing the HttpService
from the @nestjs/common
library. However, I consistently encounter a 400 Bad Request error.
Here’s the code using HttpService to get JWT token:
import {
HttpService,
InternalServerErrorException,
} from "@nestjs/common";
export class JwtService {
constructor(private httpService: HttpService, private cache: CacheService) {}
private getAuthToken(): Observable<OAuth> {
const url = 'endpoint_url';
const body = JSON.stringify({
"client_id": 'XXXXXXXXXXXXXXX',
"client_secret": 'XXXXXXXXXXXXX',
"grant_type": "client_credentials",
});
const headers = { "Content-Type": "application/json" };
return this.callAPI(url, body, headers);
}
private callAPI(
url: string,
body,
headers: { [key: string]: string }
): Observable<any> {
return this.httpService.post(url, body, headers).pipe(
map((result: AxiosResponse<any>) => result.data),
tap((result: any) => {
const { access_token } = result; // eslint-disable-line
this.cache
.set("authToken", access_token, {
ttl: env.SECONDS_TO_EXPIRE,
})
.subscribe();
}),
catchError((err: any) => {
return throwError(
new InternalServerErrorException(err.message, "Auth Service")
);
})
);
})
}
}
}
Here’s what I’ve already tried:
- Other APIs: I tested the same code with other APIs, and it worked flawlessly. The issue seems specific to the JWT token API.
- Postman Success: When I manually send the request using Postman (same URL, body, and headers), I successfully receive the token.
- Body Format: I attempted using a plain object for the request body instead of a JSON object, but the error persists.
- Fetch API: I also experimented with the
fetch()
API, and it returned the expected response (code snippet below).
Sample code using fetch api:
const req = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
client_id: XXXXXXXXXX,
client_secret: XXXXXXXXXXX,
grant_type: XXXXXXXXXXX,
}),
};
fetch('jwt_token_endpoint', req)
.then((response) => response.json())
.then((data) => {
this.logger.log(`Success retrieving jwt token`);
console.log(data);
this.jwtSubject.next(`${data.token}`);
})
.catch((error) => {
this.logger.error(`Error retrieving jwt token: ${error}`);
});
I am looking for an assistance to resolve the error and get the token successfully.