2016-12-06 191 views
0

的身体我想POST到我的服务器上的API端点。我知道我的终点工作,因为如果我使用高级REST客户端,我可以打它,并得到一个JSON响应预期。这个问题似乎是没有数据在我的请求主体发送,尽管调用request.write(postData)其中包含一个键,值对。如果没有在正文中发送这些数据,我的服务器将按照预期返回401错误,但没有此信息。打印出来的POST服务器端的内容是空的,但我无能,为什么它是空的。HTTPS请求不发布REST请求

var postData = querystring.stringify({ 
     "access_token" : accessToken, 
     "id": applianceId 
    }); 

    var serverError = function (e) { 
     log("Error", e.message); 
     context.fail(generateControlError(requestName, "DEPENDENT_SERVICE_UNAVAILABLE", "Unable to connect to server")); 
    }; 

    var callback = function(response) { 
     var str = ""; 

     response.on("data", function(chunk) { 
      str += chunk.toString("utf-8"); 
     }); 

     response.on("end", function() { 
      result = generateResult(CONTROL, requestName.replace("Request", "Confirmation"), messageId); 

      context.succeed(result); 
     }); 

     response.on("error", serverError); 
    }; 

var options = { 
    hostname: REMOTE_CLOUD_HOSTNAME, 
    port: 443, 
    path: REMOTE_CLOUD_BASE_PATH + "/" + endpoint, 
    method: "POST", 
    headers: { 
     "Content-Type": "application/x-www-form-urlencoded" 
    } 
}; 

var request = https.request(options, callback); 

request.on("error", serverError); 

//This doesn't seem to write anything since if I print out the POST 
//data server-side it's empty; however, if I print out the value of 
//postData here, it looks as expected: 'access_token=xxxxx' 
request.write(postData); 

request.end(); 

回答

0

我再次测试你的代码httpbin.org/post,似乎这是工作。 我相信有关,你应该张贴application/json,而不是“application/x-www-form-urlencoded

请尝试更改标题

​​

然后,尝试将POSTDATA更改为JSON字符串的问题:

var postData=JSON.stringify({access_token:"xxxxx"}) 

为了确保您成功发送的问题和问题不在本地(可能是您的服务器存在问题),请将目标更改为镜像URL:

var options = { 
    hostname: "httpbin.org", 
    path:'/post', 
    port: 443, 
    method: "POST",  
    headers: { 
     "Content-Type": "application/json" 
    } 
}; 

如果在你的NodeJS版本没问题,是你应该得到的回应:(这是意味着服务器得到了公布数据)

{ 
    "args": {}, 
    "data": "{\"access_token\":\"xxxxx\"}", 
    "files": {}, 
    "form": {}, 
    "headers": { 
    "Content-Length": "24", 
    "Content-Type": "application/json", 
    "Host": "httpbin.org" 
    }, 
    "json": { 
    "access_token": "xxxxx" 
    }, 
    "origin": "5.29.63.30", 
    "url": "https://httpbin.org/post" 
} 

BTW:我真的建议你移动到库来管理你的要求:

+0

感谢您的答复的人。不幸的是,问题不会切换到JSON来解决,因为我有它在ARC当前内容类型的工作。它在AWS上运行,所以我怀疑是否有服务器问题。由于某种原因,发布的数据似乎并未在我的实施中发送。 – roundtheworld

+0

我已经测试您的实现。它正在工作。所以它与你发布的代码无关 – Aminadav