Send Http Request with cookie using CookieJar
Some services are checking the request with cookie to increase the security.
So sometime you make a request successful with Postman, but got 403 (or similar error code) when try to request from your server (or a simple CURL request).
That because Postman auto detect and add cookie if needed for the request.
Using CookieJar will help you do the similar thing:
Install
npm install axios tough-cookie axios-cookiejar-support
Then using a wraper axios to send the request instead.
import axios from 'axios';
import { CookieJar } from 'tough-cookie';
import { wrapper } from 'axios-cookiejar-support';
import { AxiosInstance } from 'axios';
@Injectable()
export class AppService {
private axiosClient: AxiosInstance;
constructor() {
const jar = new CookieJar();
this.axiosClient = wrapper(axios.create({ jar }));
}
async getActiveCode(courseId: string) {
try {
await this.axiosClient.get("simple-get-request-to-save-cookie", configs);
const response = await this.axiosClient.get(url, configs);
return response.data;
} catch (error) {
console.log({ error: error.message });
}
}
}
NOTE: You have to make 1 simple request that does not require cookie so it able to get the cookie from that request! Meaning you always have to have 2 requests!!!
(So you have to create your own re-try mechanism to optimize this!)