【问题标题】:x-www-form-urlencoded format - using https in node.jsx-www-form-urlencoded 格式 - 在 node.js 中使用 https
【发布时间】:2021-11-02 17:48:27
【问题描述】:

我目前正在写入 API 以尝试获取令牌。我快到了,但在最后一道障碍中摔倒了..

const fs = require('fs');
const https = require('https');
const ConfigParams = JSON.parse(fs.readFileSync('Config.json', 'utf8'));
const jwt = require('jsonwebtoken');
const apikey = ConfigParams.client_id;


var privateKey = fs.readFileSync(**MY KEY**);
var tkn;

const jwtOptions = {
    algorithm: 'RS512',
    header: { kid: 'test-1' }
}


const jwtPayload = {
    iss: apikey,
    sub: apikey,
    aud: **API TOKEN ENDPOINT**,
    jti: '1',
    exp: 300
}

jwt.sign(jwtPayload,
    privateKey,
    jwtOptions,
    (err, token) => {
        console.log(err);
        //console.log(token);
        tkn = token;

        let = tokenPayload = {
            grant_type: 'client_credentials',
            client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer/',
            client_assertion: tkn
        }

        tokenAuthOptions = {
            payload: tokenPayload,
            host: **HOST**,
            path: **PATH**,
            method: 'POST',
            

        }
          
        https.request(
            tokenAuthOptions,
            resp => {
                var body = '';
                resp.on('data', function (chunk) {
                    body += chunk;
                });
                resp.on('end', function () {
                    console.log(body);
                    console.log(resp.statusCode);
                });
            }
        ).end(); 
    }
)

编码的令牌在第一部分恢复正常,但 https 请求返回问题。

我得到的响应是缺少 grant_type,所以我知道由于这个 x-www-form-urlencoded,我遇到了格式问题,但我不知道如何解决它。

这是网站所说的:

您需要在请求正文中包含以下数据 x-www-form-urlencoded 格式:

grant_type = client_credentials client_assertion_type = urn:ietf:params:oauth:client-assertion-type:jwt-bearer client_assertion = 这是一个完整的 例如,作为 CURL 命令:

curl -X POST -H "content-type:application/x-www-form-urlencoded" --data \ "grant_type=client_credentials\ &client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer
&client_assertion="
终点

理想情况下,我想要一个使用 https 请求的解决方案,但如果这不可能,我愿意接受其他解决方案。

非常感谢任何帮助。

谢谢, 克雷格

编辑 - 我根据以下建议更新了我的代码:

const params = new url.URLSearchParams({
    grant_type: 'client_credentials',
    client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer/',
    client_assertion: tkn
});

axios.post("URL", params.toString()).then(resp => {
    console.log("response was : " + resp.status);
}).catch(err => {
    console.log("there was an error: " + err);
})

但我仍然收到错误代码 400,但现在没有详细说明原因。 (错误码400有多个消息失败)

【问题讨论】:

  • 我在这里看不到选项payloadnodejs.org/api/http.html#httprequestoptions-callback。最好使用gotaxios 之类的东西来发送此类请求。另外,请记住,对于 x-www-form-urlencoded 的正文,它不应该是 JSON,它应该是一个特殊的字符串。
  • 感谢您的信息。我会尝试 Axios 而不是 https。如果有人以前做过类似的事情并且可以协助格式化,那就太好了。
  • 也许像 axios 一样准备一个字符串就足够了,见这里github.com/axios/…
  • 我刚上同一个网站 :) 我改成axios,改在主帖里。不幸的是,我现在在 catch 中收到错误 400,它给我的响应代码错误信息更少:(
  • 因为您在 Node.js 中而不是在浏览器中执行所有这些操作,所以您需要使用 qs:github.com/axios/axios#nodejs

标签: node.js api


【解决方案1】:

邮递员是最好的。

感谢@Anatoly 的支持,它帮助我指明了正确的方向。我运气不好,第一次用 postman,发现它有一个代码 sn-p 部分,使用 node.js 有四种不同的方式来实现。

Axion 的解决方案是:

const axios = require('axios').default;
const qs = require('qs');

        var data = qs.stringify({
            'grant_type': 'client_credentials',
            'client_assertion_type': 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
            'client_assertion': tkn
        });
        var config = {
            method: 'post',
            url: '',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            data: data
        };

        axios(config)
            .then(function (response) {
                console.log(JSON.stringify(response.status));
            })
            .catch(function (error) {
                console.log(error);
            });

我认为问题在于我没有将信息传递到“数据:”中并结合查询字符串问题。使用 qs.stringify 格式化对象,然后将其传递到数据中:key 解决了问题。

【讨论】:

    猜你喜欢
    • 2021-06-27
    • 2019-01-03
    • 2011-09-13
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 2014-03-30
    • 2019-02-04
    相关资源
    最近更新 更多