【发布时间】:2026-01-26 17:10:01
【问题描述】:
我有一个 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。我怎样才能抓住它?
【问题讨论】:
-
我们能看到
options对象吗?另外,你期待二进制数据吗? -
嗨 ishegg - 更新为包含选项对象。返回的数据不是二进制的,要么没有返回任何状态为 200 的数据,要么我认为是包含我包含的 JSON 的正文。
标签: javascript node.js httprequest