Node JS Request在控制台中不打印任何内容

时间:2018-03-20 13:44:19

标签: node.js api request

我正在使用post nodejs模块进行requests来电。但是,console.log语句似乎不适用于我想要获得的errorresponse.body

我的POST请求需要以下标题 -

Accept : "application/json"
Content-Type : "application/json"
Authorization : Basic + Base64Encoded(username+password)

post body就是这样的

体:

{
   "arg_1" : "a_string_key"
  , "arg_2" : "a_string"
  , "arg_3" : "a_string"
  , "arg_4" : "some_value"
  , "arg_5" : "some_string"
  , "arg_6" : "<yyyy-mm-dd>"
  , "arg_7" : "<yyyy-mm-dd>"
}

我的代码除了发送POST请求并检查response.statusCode ==200

之外什么都不做

这就是我正在做的事情

var int_user = "username";
var int_pass = "password";
var encoding = "base64"

var auth = "Basic" + new Buffer(int_user + int_pass).toString(encoding);

var headers = {
  "Accept": "application/json",
  "Content-Type": "application/json",
  "Authorization": auth
}

var options = {
  url: 'URL_I_WANT',
  // method: 'POST',
  headers: headers,
  body : {
    "arg_1": "a_string_key",
    "arg_2": "a_string",
    "arg_3": "a_string",
    "arg_4": "some_value",
    "arg_5": "some_string",
    "arg_6": "<yyyy-mm-dd>",
    "arg_7": "<yyyy-mm-dd>"
  },
  json: true
}

console.log('Before request');

request.post(options, function(error, response) {
  if (error) {
    console.log(error);
  }
  try {
    if (!error && response.statusCode == 200) {
      console.log(response.body);
      console.log('Success');
    }
  } catch (error) {
    console.log(error)
  }
});

console.log('After request');

代码运行没有任何故障,我得到beforeafter请求控制台语句。但是,请求中的语句不会出现在控制台中,这意味着我的请求不会通过。我无法理解这一点。如果请求本身存在问题,是否应该出现错误?如果请求失败,为什么不打印出error

1 个答案:

答案 0 :(得分:0)

这可能是因为您的节点进程是自动关闭的,它将在异步请求完成之前退出(没有查看它但可能是可配置的)。我在repl.it上看过这样的设置。

要克服这个问题(如果不可配置),您可以将代码包装在异步函数中,并使用request-promise来调用await请求。

var request = require('request-promise-native');


var int_user = "username";
var int_pass = "password";
var encoding = "base64"

var auth = "Basic" + new Buffer(int_user + int_pass).toString(encoding);

var headers = {
  "Accept": "application/json",
  "Content-Type": "application/json",
  "Authorization": auth
}

var options = {
  url: 'https://google.com',
  method: 'POST',
  headers: headers,
  body : {
    "arg_1": "a_string_key",
    "arg_2": "a_string",
    "arg_3": "a_string",
    "arg_4": "some_value",
    "arg_5": "some_string",
    "arg_6": "<yyyy-mm-dd>",
    "arg_7": "<yyyy-mm-dd>"
  },
  json: true
};

console.log('Before request');

async function main() {
  try {
    const response = await request.post(options);
    if (response.statusCode === 200) {
      console.log(response.body);
      console.log('Success');
      process.exit();
    }
    console.log(`Bad statusCode:${response.statusCode}`);
  }
  catch (error) {
    console.log(error);
  }
}

main();

您可以查看以下代码

a link to the code above, working on repl.it