node.js中的两个http调用

所以我的问题是这样的。我有两个https请求。第一个请求获取访问令牌,并将其传递给第二个请求,后者从服务器获取订单信息。如果这两个请求在不同的文件中,它可以工作,但我必须手动复制访问令牌,并将其发布到第二个文件,然后运行node文件。我希望所有这些都发生在一个文件中。第一部分工作正常,我能够获得访问令牌,但随后我得到一个错误。”fault”:{“type”: “InvalidAuthorizationHeaderException”, “message”: “The request is unauthorized. 在’Authorization’头中,’Bearer’是预期的。” 先谢谢您了

const https = require('https');

var Base64 = { _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", encode: function (e) { var t = ""; var n, r, i, s, o, u, a; var f = 0; e = Base64._utf8_encode(e); while (f < e.length) { n = e.charCodeAt(f++); r = e.charCodeAt(f++); i = e.charCodeAt(f++); s = n >> 2; o = (n & 3) << 4 | r >> 4; u = (r & 15) << 2 | i >> 6; a = i & 63; if (isNaN(r)) { u = a = 64 } else if (isNaN(i)) { a = 64 } t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a) } return t }, decode: function (e) { var t = ""; var n, r, i; var s, o, u, a; var f = 0; e = e.replace(/[^A-Za-z0-9+/=]/g, ""); while (f < e.length) { s = this._keyStr.indexOf(e.charAt(f++)); o = this._keyStr.indexOf(e.charAt(f++)); u = this._keyStr.indexOf(e.charAt(f++)); a = this._keyStr.indexOf(e.charAt(f++)); n = s << 2 | o >> 4; r = (o & 15) << 4 | u >> 2; i = (u & 3) << 6 | a; t = t + String.fromCharCode(n); if (u != 64) { t = t + String.fromCharCode(r) } if (a != 64) { t = t + String.fromCharCode(i) } } t = Base64._utf8_decode(t); return t }, _utf8_encode: function (e) { e = e.replace(/rn/g, "n"); var t = ""; for (var n = 0; n < e.length; n++) { var r = e.charCodeAt(n); if (r < 128) { t += String.fromCharCode(r) } else if (r > 127 && r < 2048) { t += String.fromCharCode(r >> 6 | 192); t += String.fromCharCode(r & 63 | 128) } else { t += String.fromCharCode(r >> 12 | 224); t += String.fromCharCode(r >> 6 & 63 | 128); t += String.fromCharCode(r & 63 | 128) } } return t }, _utf8_decode: function (e) { var t = ""; var n = 0; var r = c1 = c2 = 0; while (n < e.length) { r = e.charCodeAt(n); if (r < 128) { t += String.fromCharCode(r); n++ } else if (r > 191 && r < 224) { c2 = e.charCodeAt(n + 1); t += String.fromCharCode((r & 31) << 6 | c2 & 63); n += 2 } else { c2 = e.charCodeAt(n + 1); c3 = e.charCodeAt(n + 2); t += String.fromCharCode((r & 15) << 12 | (c2 & 63) << 6 | c3 & 63); n += 3 } } return t } };
var encoded = Base64.encode("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + ":" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
var basic_auth = "Basic " + encoded;

var text = "";

const options = {
    hostname: 'hidden for security reasons',
    port: 443,
    path: 'hidden for security reasons',
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': basic_auth
    }

};

const req = https.request(options, (res) => {
    console.log("Infomation from the Auth Secure Client API CALL");
    console.log('statusCode:', res.statusCode);
    console.log('headers:', res.headers);
    console.log("THE CALL ENDS HERE");

    res.on('data', (d) => {
        //process.stdout.write(d);// here I was testing that I get body from the server
        text = JSON.parse(d);
        text = text.access_token;
        //process.stdout.write(text); // printing the access_token making sure that I get it
    })
});

req.on('error', (error) => {
    console.error(error)
});

req.end();

const data = JSON.stringify({
    "query":
    {
        "text_query": { "fields": ["customer_email"], "search_phrase": "martin@test.com" }
    },
    "select": "(**)",
    "sorts": [{ "field": "customer_name", "sort_order": "asc" }]
});

var auth = 'Bearer ' + text;

const options2 = {
    hostname: 'hidden for security reasons',
    port: 443,
    path: 'hidden for security reasons',
    method: 'POST',
    headers: {
        'x-dw-client-id': 'hidden for security reasons',
        'Content-Type': 'application/json',
        'Content-Length': data.length,
        'Authorization': 'Bearer ' + text
    }
};


const req2 = https.request(options2, (res) => {
    console.log('statusCode:', res.statusCode);
    console.log('headers:', res.headers);

    res.on('data', (d) => {
        process.stdout.write(d)
    })
});

req2.on('error', (error) => {
    console.error(error)
});

req2.write(data);
req2.end();

解决方案:

很好,你正在使用本地模块进行网络调用。HTTPS是基于事件的,主要有 “data”、”error”、”end “等事件。在执行https调用后,我们会得到分块的数据。当’end’事件被触发时,意味着https调用已经完成,我们已经收到了所有的数据块。

由于Node.js是异步的,所有的IO调用都由工作线程处理,主线程继续执行代码。由于这里你对第一个http调用有依赖性,所以你必须等待它完成。

你可以使用其他模块,这样可以使生活更轻松,但在你学习和理解其工作的早期阶段,本地模块是很好的。

const req = https.request(options, (res) => {
        console.log("Infomation from the Auth Secure Client API CALL");
        console.log('statusCode:', res.statusCode);
        console.log('headers:', res.headers);
        console.log("THE CALL ENDS HERE");

        res.on('data', (chunk) => {
            //process.stdout.write(d);// here I was testing that I get body from the server
            text += chunk;
            text = text.access_token;
            //process.stdout.write(text); // printing the access_token making sure that I get it
        });
        
        res.on('end', () => {
            text = JSON.parse(text);
            access_token = text.access_token;
            // after the first https request is complete, we will call the second https request
            secondCall(access_token);
        });
        
    });

    //Making second https call
    const secondCall = (access_token) => {
        const options2 = {
          hostname: 'hidden for security reasons',
          port: 443,
          path: 'hidden for security reasons',
          method: 'POST',
          headers: {
              'x-dw-client-id': 'hidden for security reasons',
              'Content-Type': 'application/json',
              'Content-Length': data.length,
              'Authorization': 'Bearer ' + access_token 
          }
      };
      
      //Now here you can call the second request 
      
    }

给TA打赏
共{{data.count}}人
人已打赏
未分类

通过读取文本文件创建列表

2022-9-8 21:27:38

未分类

材质 UI Fab 按钮停留在左侧分割窗格下。

2022-9-8 21:27:40

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索