必须提供grant_type错误invalid_request

时间:2020-05-05 07:03:22

标签: javascript post oauth-2.0 postman request-headers

我总是使用以下JS脚本收到“ grant_type是否为必需的错误invalid_request”信息,但我不知道为什么:

let tokenUrl = 'myTokenURL';
let clientId = 'myClientID';
let clientSecret = 'myClientSecret';
let scope = 'myScope';

let getTokenRequest = {
    method: 'POST',
    url: tokenUrl,
    auth: {
        type: "basic",
        basic: [
            { key: "username", value: clientId },
            { key: "password", value: clientSecret }
        ]
    },
    header: {
        'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: {
        mode: 'formdata',
        formdata: [
            { key: "grant_type", value: "authorization_code" },
            { key: 'scope', value: scope },
            { key: 'redirect_uri', value: 'MyRedirectURI' },
            { key: 'client_id', value: clientId},
            { key: 'clientSecret', value: clientSecret},
        ]
    }
};


pm.sendRequest(getTokenRequest, (err, response) => {
    let jsonResponse = jsonResponse = response.json();;    
    let newAccessToken = jsonResponse.access_token;

    console.log({ err, jsonResponse, newAccessToken })
});

这是使用Postman sendRequest函数

1 个答案:

答案 0 :(得分:0)

对于所有对此解决方案感兴趣的人,请参见以下代码,实际上是以上评论中Danny Daiton的答案

let tokenUrl = 'myTokenURL';
let clientId = 'myClientID';
let clientSecret = 'myClientSecret';
let scope = 'myScope';

let getTokenRequest = {
    method: 'POST',
    url: tokenUrl,
    auth: {
        type: "basic",
        basic: [
            { key: "username", value: clientId },
            { key: "password", value: clientSecret }
        ]
    },
    header: {
        'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: {
        mode: 'urlencoded',
        urlencoded: [
            { key: "grant_type", value: "authorization_code" },
            { key: 'scope', value: scope },
            { key: 'redirect_uri', value: 'MyRedirectURI' },
            { key: 'client_id', value: clientId},
            { key: 'clientSecret', value: clientSecret},
        ]
    }
};


pm.sendRequest(getTokenRequest, (err, response) => {
    let jsonResponse = jsonResponse = response.json();;    
    let newAccessToken = jsonResponse.access_token;

    console.log({ err, jsonResponse, newAccessToken })
});