Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to POST form-data using HttpModule in NestJS

I am trying to get an access token from Instagram API. I'm want to send the body as form-data. This is my code. this is not working. but it works fine in postman.

async getAccessTokenByCode(code: string): Promise<string> {

    const baseUrl = config.get('authorize.baseUrl');
    const clientId =  config.get('basic.clientId');
    const clientSecret = config.get('basic.clientSecret');
    const grantType = config.get('basic.grant_type');
    const redirectUri = config.get('basic.redirect_uri');

    const url = `${baseUrl}/oauth/access_token`

    const form = new FormData();
    form.append('client_id', clientId);
    form.append('client_secret', clientSecret);
    form.append('grant_type', grantType);
    form.append('redirect_uri', redirectUri);
    form.append('code', code);


    try {
        const response = await this.httpService.post(url, { data: form }, {  headers: form.getHeaders() }).toPromise();
        return response.data;
    } catch (error) {
        console.log(error);
    }
}

How to properly send post data using NestJS HttpModule??

like image 314
Buddhika Nelum Avatar asked Jun 25 '26 07:06

Buddhika Nelum


2 Answers

Here is the my working code:

async getAuthToken() {
    const url = this.configService.get<string>('AUTHTOKEN_URL');
    var bodyFormData = new FormData();
    bodyFormData.append('SCOPE', this.configService.get<string>('SCOPE'));
    bodyFormData.append('EMAIL_ID', this.configService.get<string>('EMAIL_ID'));
    bodyFormData.append('PASSWORD', this.configService.get<string>('PASSWORD'));

    const response = await this.httpService.post(
      url,
      bodyFormData,
      { headers: bodyFormData.getHeaders() }
    ).toPromise();
    console.log(response.data);
    return response.data;
  }

Second argument is not json its just data in your case

like image 111
Hassan Ali Shahzad Avatar answered Jun 28 '26 03:06

Hassan Ali Shahzad


I had to format the data manually. I am not sure how to do that properly in NestJS. I haven't found a module like qs, for example, that I would have used in NodeJS.

const data = `client_id=${clientId}&client_secret=${clientSecret}&grant_type=${grantType}&redirect_uri=${redirectUri}&code=${code}`;
like image 25
mbuessecker Avatar answered Jun 28 '26 03:06

mbuessecker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!