To send a https request to a rest service in Node, we use the https.request method.
For instance, we write
const https = require("https");
const options = {
hostname: "www.example.com",
port: 443,
path: "/",
method: "GET",
headers: {
Accept: "plain/html",
"Accept-Encoding": "*",
},
};
const req = https.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`);
console.log("headers:", res.headers);
res.on("data", (d) => {
process.stdout.write(d);
});
});
req.on("error", (error) => {
console.error(error);
});
req.end();
to call https.request with the options object to make a request to https://www.example.com.
The object has the headers, the request method, the port and the path.
We get the response from res in the callback.
We get the status code with res.statusCode.
We get the response headers with res.headers.
And we get the response body from the data event callback’s d parameter.
We get errors from the error parameter from the error event handler.