如何检索HTTP响应错误的详细信息

我有一个node.js应用程序正在向ReST Web服务发出一些https请求。 我想做一些事情,表面上看起来应该很简单 – 检索Web服务返回的错误消息。

我可以得到状态代码 – 即200,404等,但不是错误的细节。

响应的主体看起来像这样:

{ "type": "http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.5", "title" : "Not Found", "status": "404", "detail": "Resource not found: X33003" } 

我的代码如下所示:

 var options = { "method": "POST", "hostname": "myhost.com", "port": null, "path": "/mypath/", "headers": { "content-type": "application/json", "authorization": basicAuthString, "cache-control": "no-cache" } }; try { var reqWorkSkill = http.request(options, function(res) { var chunks = []; res.on("data", function(chunk) { chunks.push(chunk); }); res.on("end", function() { var body = Buffer.concat(chunks); var response = JSON.parse(body); console.log("Detail: " + body.detail); // COMES BACK UNDEFINED }); res.on("error", function(error) { console.log("Something went wrong with: " + resourceIdArray[i] + " failed: " + error); }); if(res.statusCode != 200){ // Do some stuff } console.log("res status: " + res.statusCode); console.log("res text: " + res.statusText); // COMES BACK UNDEFINED }); reqWorkSkill.write(itemToPost); reqWorkSkill.end(); } catch (e) { console.log(e); } 

能够展示出现错误的信息将会很有用 – 即消息:Resource not found:来自上面的JSON的X33003。 我怎么能得到这个?

你只是有你正在调用的对象的错误属性。 首先,你调用body.detail ,但是bodyBuffer表示。 您需要在response调用detail属性。 其次,您试图获取响应的statusText属性,但正确的属性是statusMessage 。 代码结束如下所示:

 var options = { "method": "POST", "hostname": "myhost.com", "port": null, "path": "/mypath/", "headers": { "content-type": "application/json", "authorization": basicAuthString, "cache-control": "no-cache" } }; try { var reqWorkSkill = http.request(options, function(res) { var chunks = []; res.on("data", function(chunk) { chunks.push(chunk); }); res.on("end", function() { var body = Buffer.concat(chunks); var response = JSON.parse(body); console.log("Detail: " + response.detail); // response, not body }); res.on("error", function(error) { console.log("Something went wrong with: " + resourceIdArray[i] + " failed: " + error); }); if(res.statusCode != 200){ // Do some stuff } console.log("res status: " + res.statusCode); console.log("res text: " + res.statusMessage); // statusMessage, not statusText }); reqWorkSkill.write(itemToPost); reqWorkSkill.end(); } catch (e) { console.log(e); } 

如果你没有得到正确的结果,那么console.log (或者等效的)对象就是一个好主意,它会显示对象的所有属性。