node.js中的两个http调用

node.js中的两个http调用,node.js,Node.js,所以我的问题是这个。我有两个https请求。第一个请求获取AccessToken并将其传递给第二个请求,该请求从服务器获取订单信息。如果这两个请求位于不同的文件中,它可以工作,但我必须手动复制访问令牌,将其发布到第二个文件,然后运行节点文件。我希望所有这些都发生在一个文件中。第一部分工作正常,我能够获得访问令牌,但随后我得到一个错误。“fault:{”type:“InvalidAuthorizationHeaderException”,“message:“请求未经授权。在“Authorizati

所以我的问题是这个。我有两个https请求。第一个请求获取AccessToken并将其传递给第二个请求,该请求从服务器获取订单信息。如果这两个请求位于不同的文件中,它可以工作,但我必须手动复制访问令牌,将其发布到第二个文件,然后运行节点文件。我希望所有这些都发生在一个文件中。第一部分工作正常,我能够获得访问令牌,但随后我得到一个错误。“fault:{”type:“InvalidAuthorizationHeaderException”,“message:“请求未经授权。在“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();
consthttps=require('https');
var Base64={{u keyStr:“abcdefghijklmnopqrstuvxyzabefghijklmnopqrstuvxyzo123456789+/=”,编码:函数(e){var t=“”;var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_编码(e);而(f2;o=2;u=6;>i>(isNaN(r)){u=a=64}否则如果(isNaN(i)){a=64}t=t+this.[u keyStr.charAt(s)+this.[u keyStr.charAt(o)+this.[u keyStr.charAt(u)+this.[u keyStr.charAt(a)}返回t},解码:函数(e){var t=”“;var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^a-Za-z0-z0+=”)/g;[e];而这个长度4;r=(o&15)>2;i=(u&3)127&r<2048){t+=String.fromCharCode(r>>6 | 192);t+=String.fromCharCode(r&63 | 128}=String(r&12412){(r>>6&63 | 128);t+=String.fromCharCode(r&63 | 128)}返回t},utf8\u解码:函数(e){var t=“”;var n=0;var r=c1=c2=0;而(n191&&r<224){c2=e.charCodeAt(n+1);t=charCodeAt(=31){
控制台错误(错误)
});
请求结束();
const data=JSON.stringify({
“查询”:
{
“文本查询”:{“字段”:[“客户电子邮件”],“搜索短语”:martin@test.com" }
},
“选择”:“(**”),
“排序”:[{“字段”:“客户名称”,“排序顺序”:“asc”}]
});
var auth=‘承载人’+文本;
常量选项2={
主机名:“出于安全原因而隐藏”,
港口:443,
路径:“出于安全原因而隐藏”,
方法:“POST”,
标题:{
“x-dw-client-id”:“出于安全原因而隐藏”,
“内容类型”:“应用程序/json”,
“内容长度”:data.Length,
“授权”:“持有人”+文本
}
};
const req2=https.请求(选项2,(res)=>{
console.log('statusCode:',res.statusCode);
log('headers:',res.headers);
res.on('数据',(d)=>{
进程.标准输出.写入(d)
})
});
请求2.on('错误',(错误)=>{
控制台错误(错误)
});
请求2.写入(数据);
请求2.结束();

如评论中所述,您不会等待一个查询完成后再进行另一个查询

这里有一个快速的重新公式

  • 用于发出请求的基于承诺的包装器(很可能有问题,嗯)
  • 链接两个调用的异步函数
  • 如何从非异步上下文调用承诺返回异步函数的示例
希望这有帮助

const https = require("https");

function requestP(options, data = null) {
  return new Promise((resolve, reject) => {
    const req = https.request(options, res => {
      let data = "";
      res.on("data", d => (data += d));
      res.on("end", () => {
        resolve({ res, data });
      });
    });
    req.on("error", reject);
    if (data) req.write(data);
    req.end();
  });
}

async function doThings() {
  const r1 = await requestP({
    hostname: "hidden for security reasons",
    port: 443,
    path: "hidden for security reasons",
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      Authorization: "Basic ...",
    },
  });
  const accessToken = JSON.parse(r1.data).access_token;
  const data = JSON.stringify({
    query: {
      text_query: {
        fields: ["customer_email"],
        search_phrase: "martin@test.com",
      },
    },
    select: "(**)",
    sorts: [{ field: "customer_name", sort_order: "asc" }],
  });
  const r2 = await requestP({
    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 " + accessToken,
    },
  }, data);
  return r2;
}

doThings().then(result => {
  console.log(result);
});


正如在评论中提到的,您不会等待一个查询完成后再进行另一个查询

这里有一个快速的重新公式

  • 用于发出请求的基于承诺的包装器(很可能有问题,嗯)
  • 链接两个调用的异步函数
  • 如何从非异步上下文调用承诺返回异步函数的示例
希望这有帮助

const https = require("https");

function requestP(options, data = null) {
  return new Promise((resolve, reject) => {
    const req = https.request(options, res => {
      let data = "";
      res.on("data", d => (data += d));
      res.on("end", () => {
        resolve({ res, data });
      });
    });
    req.on("error", reject);
    if (data) req.write(data);
    req.end();
  });
}

async function doThings() {
  const r1 = await requestP({
    hostname: "hidden for security reasons",
    port: 443,
    path: "hidden for security reasons",
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      Authorization: "Basic ...",
    },
  });
  const accessToken = JSON.parse(r1.data).access_token;
  const data = JSON.stringify({
    query: {
      text_query: {
        fields: ["customer_email"],
        search_phrase: "martin@test.com",
      },
    },
    select: "(**)",
    sorts: [{ field: "customer_name", sort_order: "asc" }],
  });
  const r2 = await requestP({
    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 " + accessToken,
    },
  }, data);
  return r2;
}

doThings().then(result => {
  console.log(result);
});


发送http请求是一项异步任务。因此它可能需要不同的时间。在这种情况下,您的第二个请求在第一个请求之前完成。请使用类似于
axios
的模块来处理请求

const axios = require('axios');

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
  }

};

axios(options)
  .then(res => {
    console.log(res);
    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
      }
    };
    return axios(options2);
  })
  .then(res => {
    console.log(res);
  })
  .catch(err => {
    console.log(err);
  });
const axios=require('axios');
var Base64={{u keyStr:“abcdefghijklmnopqrstuvxyzabefghijklmnopqrstuvxyzo123456789+/=”,编码:函数(e){var t=“”;var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_编码(e);而(f2;o=2;u=6;>i>(isNaN(r)){u=a=64}否则如果(isNaN(i)){a=64}t=t+this.[u keyStr.charAt(s)+this.[u keyStr.charAt(o)+this.[u keyStr.charAt(u)+this.[u keyStr.charAt(a)}返回t},解码:函数(e){var t=”“;var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^a-Za-z0-z0+=”)/g;[e];而这个长度4;r=(o&15)>2;i=(u&3)127&r<2048){t+=String.fromCharCode(r>>6 | 192);t+=String.fromCharCode(r&63 | 128}=String(r&12412){(r>>6&63 | 128);t+=String.fromCharCode(r&63 | 128)}返回t},utf8\u解码:函数(e){var t=“”;var n=0;var r=c1=c2=0;而(n191&&r<224){c2=e.charCodeAt(n+1);t=charCodeAt(=31){
控制台日志(err);
});

发送http请求是一项异步任务。因此,它可能需要不同的时间。在这种情况下,您的第二个请求在第一个请求之前完成。请使用类似于
axios
的模块来处理请求

const axios = require('axios');

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
  }

};

axios(options)
  .then(res => {
    console.log(res);
    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
      }
    };
    return axios(options2);
  })
  .then(res => {
    console.log(res);
  })
  .catch(err => {
    console.log(err);
  });
const axios=require('axios');
var Base64={u keyStr:“abcdefghijklmnopqrstuvxyzabefghijklmnopqrstuvxyz012456789+/=”,编码:函数(e){var t=“”;var n,r,i,s,o,u,a;var f=0;e=Base64.\u utf8_编码(e);而(f