首页 > 解决方案 > 如何在 NestJS 中使用 HttpModule 发布表单数据

问题描述

我正在尝试从 Instagram API 获取访问令牌。我想将正文作为表单数据发送。这是我的代码。这是行不通的。但它在邮递员中工作正常。

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 正确发送帖子数据?

标签: postaxiosnestjsmernhttpmodule

解决方案


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

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

推荐阅读