Follow up. Since data might be in chunks the following code would work better
{
console.log("Status Code:", res.statusCode);
let data = [];
res.setEncoding("utf8");
res.on("data", (chunk) => {
data.push(chunk);
});
res.on("end", () => {
console.log("Body: ", JSON.parse(data));
});
}
Here is also how you would do it against a “real” url (not localhost)
// The default http package that node uses.
// There are a lot of alternatives to http that might be a bit easier to work with.
const http = require("https"); // The http package doesn't work with https. Switch to the https package for https.
const req = http.request(
{
host: "random.url.io",
path: "/api/users",
method: "GET",
auth: "mylogin@something.com:MyRandomPassword", // Change this to the actual admin user and password
},
(res) => {
console.log("Status Code:", res.statusCode);
let data = [];
res.setEncoding("utf8");
res.on("data", (chunk) => {
data.push(chunk);
});
res.on("end", () => {
console.log("Body: ", JSON.parse(data));
});
}
);
req.on("error", (err) => {
console.log("Error: ", err.message);
});
req.end();