-1

我创建了以下 NodeJS 函数。

我遇到的问题是,当我执行以下代码时:

someFunc(parameter)
.then(function(doSomething){
  //do something here, which works fine here.
})
//The following function works and is very similar to the next function.
.then(someFunc1)
//
.then(impervaCreateIP)
//
//The following function works and is very similar to the above function.
.then(someFunc3)
.catch(function(e){
  //catch error here. This works too.
})

并调用下面的函数,它给了我一个错误:

[SyntaxError: Unexpected end of input]

出现此错误的原因是,在函数 (someFunc1) 成功完成后控件转到impervaCreateIP()时,然后在impervaCreateIP()内部,正在执行以下行(正在等待 REST/API 调用以创建新的操作系统Imperva 系统中的连接 IP)。

  httpHelp(options, data)
  .then(function(fullResponse){
    var result = JSON.parse(fullResponse[1])

正如您在上面看到的,一旦调用 httpHelp(options,data).then(function(fullResponse){ ... } 部分,如果我在下一行之前打印( console.log("anything") ),它就是显示该消息很好。但是,在以下行之后没有打印任何内容,原因:fullResponse [1]没有得到填充或没有得到任何有效值,到下一行以异步方式执行时。这导致程序运行直接进入 .fail(...){ .. } 部分,然后进入 someFunc3 (它没有做任何事情,因为在 impervaCreateIP 期间捕获的异常并最终到达 .catch(...){ .. } 部分和做我在那里做的任何事情。

    var result = JSON.parse(fullResponse[1])

因此,程序在.parse处出错字符,即它无法解析变量结果的任何内容,因为fullResponse[1]值仍设置为“”(空白/NULL)并且尚未填充。

如何,我可以让我的程序等待,即直到 httpHelp(..).then(function(fullResponse) {....} 完全完成与 REST/API 调用的工作,它在fullResponse[1中返回一个有效值]

PS:我看到 fullResponse[0].statusCode == 200,所以连接很好。

代码:

//Imperva create IP
//qData is a hash array that has valid index/value pair values.
var impervaCreateIP = function(qData){
  var deferred = Q.defer();
  var data = '{"connection-mode":"SSH","host-name":"server123.company.com"}'
  var options = {
    hostname: 'myImpervaServerInstance.mycompanydomain.com',
    port: 8083,
    method: 'POST',
    path: '/SecureSphere/api/v1/conf/serverGroups/'+ qData['siteName'] + '/' + qData['serverGroupName'] + '/servers/' + qData['ip'],
    headers: {
      'Content-Type': 'application/xml',
      'X-Requested-With': 'Nodejs',
      'Cookie': 'JSESSIONID='+qData['sid']
    }
  }
  //svtLog() is a logger that I'm using to log messages to a file. Out of scope of this post.
  svtLog('info','Imperva','Inside impervaCreateIP function')
  svtLog('info','Imperva',qData['ip'])
  svtLog('info','Imperva',qData['siteName'])
  svtLog('info','Imperva',qData['serverGroupName'])
  console.log('Inside impervaCreateIP')
  console.log(options);
  httpHelp(options, data)
  .then(function(fullResponse){
    //The following section is not executing
    console.log("00 ---- this will print fine")
    var result = JSON.parse(fullResponse[1])
    //The following section is not executing. It going straight to .catch() as the above line failed at .parse(fullResponse[1]) where fullResponse[1] is coming as BLANK.
    console.log("11 -----")
    console.log(result)
    console.log("22 -----")
    deferred.resolve(qData)
    console.log(result)
  })
  .fail(function(e){
    svtLog('error','Imperva','Failed to add IP in Imperva')
    svtLog('info','Imperva',qData['ip'])
    svtLog('error','Imperva',e)
    svtLog('info','Imperva','')
    deferred.reject(e)
  })
  return deferred.promise;
}

在 someFunc1/3 或 ImpervaCreateIP 的情况下, fullResponse(数组值的快照是)。我只显示最后 5 行。我确保两个文件的 head -5 看起来相同,并且 fullResponse[0] 索引值也基本相似:

[vagrant@localhost ws]$ cat -n someFunc1.ip.fullResponse.json |tail -5; echo ----------------; cat -n create.ip.fullResponse.json |tail -5
   230         parser: null,
   231         res: [Circular] },
   232      read: [Function] },
   233    '{"ip":"10.20.30.40","domain":"","connection-mode":"SSH","share-name":"","folder-path":"","user-name":"enter_your_userID","host-name":"test-imperva-clientserver01.cloud.mycompany.com","OS-type":"Linux"}' ]
   234
----------------
   233         parser: null,
   234         res: [Circular] },
   235      read: [Function] },
   236    '' ]
   237
[vagrant@localhost ws]$

如果您注意到,someFunc1.ip.fullResponse.json 文件中的第 232 行和第 233 行,第 232 行结束 fullResponse[0],第 233 行开始 fullResponse[1] 值。在我的例子中,假设 someFunc1 是为了找到一个 IP,上面的输出显示,REST/API 返回值 fullResponse[1] 用于使用 Imperva REST/API(其中方法是 GET)查找 IP 的值,其余代码完全相同到 impervaCreateIP()。

如果您注意到 create.ip.fullResponse.json 文件的第 235 行和第 236 行,您会看到第 235 行结束了 fullResponse[0] 数组索引值,第 236 行开始了 fullResponse[1] 的值并具有其中有一个“”(空白/NULL),这意味着,在使用 impervaCreateIP 创建 IP 时,它没有在 fullResponse[1] 数组索引中接收到来自 Imperva REST/API 的有效响应,该索引由

var result = JSON.parse(...); // line in my NodeJS code above.

同样, someFunc1(查找 IP)或 impervaCreateIP(创建 IP)之间的唯一主要区别是,除此之外,只有 console.log("...") 消息有所改变:

对于 impervaCreateIP,它设置为:

method: 'POST',

对于 someFunc1,它设置为:

method: 'GET',

好的,看起来问题出在我的方法POST / DELETE +当我使用var result = JSON.parse(fullResponse[1])时。

如果我不尝试使用上面提到的 var result / JSON.parse 检查任何内容,我的代码可以正常工作。

所以,我认为我的根本原因是:如果我的 REST/API HTTP 方法是POSTDELETE,由于某种原因没有填充 fullResponse[1] 。如果我使用任何状态检查,例如在 impervaCreateIP(POST 操作)之后在 someFunc3(即方法为 DELETE 的 impervaDeleteSessionID)期间发生的情况,那么我的程序工作正常并且我的错误消息消失了。

但是,我确实想验证 REST 对 ex 的响应:以便我可以捕获 REST 连接是否有效 + 是否由于该用户的权限问题导致创建 IP 操作失败,该用户的凭据用于生成我的 JSESSIONID。只有当它的 POST/DELETE 并且我正在做 JSON.parse(fullResponse[1])

当 HTTP 方法是“POST”或“DELETE”并且我想捕获下面提到的条件时,如何在上面的 NodeJS 代码中获取响应正文?谢谢。

仅供参考:当我在 BASH shell 脚本中尝试相同的 impervaCreateIP NodeJS 逻辑时,我编写了以下代码并且它可以工作!!!因为如果在创建 IP 脚本期间由于该用户凭据的访问问题而出现错误,CURL 命令将返回所有输出的好坏,即带有有效的响应代码。在 NodeJS 代码中要做的就是捕捉“没有权限”错误,如果 USER 没有足够的权限在 Imperva 系统中创建 IP,则可能会出现该错误:

## Create a new IP OS connection in a given site, server group.
create_ip()
{
 JSESSIONID="${1}"
 addThisIP="${2}"
 siteName="${3}"
 serverGroupName="${4}"
 echo -e "\n- Trying to create a new OS connection IP now.\n";

 ##Make sure while initiating a REST API call, any parameter which has ' ' (space) in Imperva should be substituted with '%20'.
 create_new_ip_output="$(curl -ik -X POST -H "Cookie: JSESSIONID=$JSESSIONID" -H "Content-Type: application/json" -H "Accept: application/json" "https://${MX}:8083/SecureSphere/api/v1/conf/serverGroups/${siteName// /%20}/${serverGroupName// /%20}/servers/${addThisIP}" -d '{"connection-mode":"SSH","host-name":"thisLinuxServer.fdqn","OS-type":"linux","user-name":"enter_your_userID"}')";
 return_code="$?";
 if [[ "${return_code}" == "0" && ! `echo "${create_new_ip_output}" | grep "do not have permission"` ]]; then
  echo -e "\n\n- OS connection IP (${addThisIP}) created successfully in site: ${siteName}, servergroup: ${serverGroupName} and stdout:\n${create_new_ip_output}\n";
  return 0;
 else
  echo -e "\n\n- Failed to create a new OS connection IP (${addThisIP}) in site: ${siteName} and servergroup: ${serverGroupName}\n- using session ID: ${JSESSIONID}, error log:\n${create_new_ip_output}\n";
  return 1;
 fi
}
4

1 回答 1

0

我将深入一点来回答你为什么你关于“完成比返回更快”的假设是错误的。

javascript 的架构不允许在返回之前调用异步回调。

javascript在单个线程上有一个堆栈,函数被压入堆栈,执行,然后弹出。你不能在一个堆栈上同时做两件事。

当 javascript 遇到异步操作时,它会通过 c++ libuv 库将该操作推送到另一个线程,然后当异步操作完成时,该操作在称为回调队列的东西上返回给 javascript。只有当堆栈为空时,事件队列中的东西才会被“事件循环”推送到堆栈中。因此返回值总是首先执行,因为触发异步函数的函数仍然占用 javascript 堆栈,直到遇到返回并将函数从堆栈中弹出,使其清晰并准备好接受回调队列中的内容。

尝试登录fullResponse,看看它是否fullResponse[1]首先存在。

于 2016-06-23T00:06:51.963 回答