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

时间:2017-08-22 21:03:58

标签: javascript node.js httprequest

我有一个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);
}

能够呈现出现错误的内容是有用的 - 即消息:未找到资源:来自JSON的X33003。我怎么能掌握它?

1 个答案:

答案 0 :(得分:1)

您刚刚调用的对象属性错误。首先,您呼叫body.detail,但bodyBuffer代表。您需要在detail上调用response属性。其次,您试图获取响应的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(或等效的)你试图访问的对象总是一个好主意,它将显示对象的所有属性。