首页 > 解决方案 > 通过 node.js 服务器上的 http 请求获取 LinkedIn 访问令牌

问题描述

我正在关注授权代码流(3 条腿 OAuth)文档,现在我在第 3 步,我需要使用授权代码从 LinkedIn 接收访问令牌。在项目中,我使用的是 node.js、typescript 和node-fetch库。以下函数创建内容类型为 x-www--form-urlencoded 的正文,因为这是 LinkedIn 需要的内容类型。

async function GetAccessToken(data: any) {

    let body: string | Array<string> = new Array<string>();
    for (let property in data) {
        let encodedKey = encodeURIComponent(property);
        let encodedValue = encodeURIComponent(data[property]);
        body.push(encodedKey + "=" + encodedValue);
    }
    body = body.join("&");

    const response = await fetch("https://www.linkedin.com/oauth/v2/accessToken", {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
        body: body
    }).then((res: any) => {
        console.log("Result", res);
    });
    return response;
}

我没有收到任何错误,响应状态为 200,但我收到的响应值为:

size: 0,
timeout: 0,

LinkedIn 的承诺是:

access_token
expires_in

当我使用邮递员发布带有参数的 url 时,请求通过并且我收到正确的数据,这表明问题出在我的请求函数中,而不是我的值。

任何帮助表示赞赏!

标签: node.jstypescriptlinkedinnode-fetch

解决方案


推荐阅读