在node.js中,我正在发出POST请求,在收到POST请求的响应之前,函数正在向端点发送空格

时间:2018-01-04 23:27:17

标签: javascript node.js asynchronous

在下面的代码中,在完成后请求执行之前,将响应发送到端点。

function(req, res) {
  var details;

  getPublisherDetails() {
    getPublisherDetailsFromServer();
  }

  res.send(details);

}

getPublisherDetailsFromServer() {
  var det;
  const JSON = require('circular-json');
  var Client = require('node-rest-client').Client;
  var client = new Client();

  var args = {
    data: {
      grant_type: "client_credentials",
      client_id: "mk",
      client_secret: "Mank8"
    },
    headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    }
  };

  process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

  client.post(cache.getURL(), args, function(data, response) {
    console.log("Response from server-->" + JSON.stringify(data));
    det = data[Object.keys(data)[0]];
  });

  return det;
}

除非邮寄申请完成,否则det以上不包含任何内容

1 个答案:

答案 0 :(得分:2)

这就是js异步的工作方式。您需要在client.post回调

中发送回复
function(req,res) {

  const JSON = require('circular-json');
  var Client = require('node-rest-client').Client;
  var client = new Client();
  var args = { 
   data:                                                                                      
   {grant_type:"client_credentials",client_id:"mk" 
       ,client_secret:"Mank8"},
    headers: {"Content-Type": "application/x-www-form-urlencoded"}
   };

  process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

  client.post(cache.getURL(),args,function (data, response) {

    console.log("Response from server-->"+JSON.stringify(data));

    var det = data[Object.keys(data)[0]];
    res.send(det);

  });
}