axios 如何在NestJS中使用HttpModule对表单数据进行POST

eni9jsuy  于 2023-03-02  发布在  iOS
关注(0)|答案(3)|浏览(219)

我试图从Instagram的API获得访问令牌。我想发送的形式数据的身体。这是我的代码。这是行不通的。但它在 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);
    }
}

如何使用NestJS HttpModule?正确发送帖子数据?

sauutmhj

sauutmhj1#

下面是我的工作代码:

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;
  }

第二个参数不是json,在您的情况下它只是数据

yshpjwxd

yshpjwxd2#

我不得不手动格式化数据,我不知道如何在NestJS中正确地做这件事,我还没有找到像qs这样的模块,例如,我会在NodeJS中使用。

const data = `client_id=${clientId}&client_secret=${clientSecret}&grant_type=${grantType}&redirect_uri=${redirectUri}&code=${code}`;
72qzrwbm

72qzrwbm3#

这对我很有效。

async getToken() {

        try {

            const url = `https://login.microsoftonline.com/${this.azAdTenant}/oauth2/token`;
            const formFlat = `grant_type=client_credentials&client_id=${this.azAdClientId}&client_secret=${this.azAdClientSecret}&resource=${this.simpleStorageResource}`;

            const response = await this.http.request({
                    baseURL: url,
                    method: "POST",
                    data: formFlat,
                    headers: {'content-type': 'application/x-www-form-urlencoded'},
                }
            ).toPromise();

            return response.data;

        } catch (e) {
            return e;
        }
    }

相关问题