Skip to content

Instantly share code, notes, and snippets.

@neilstuartcraig
Last active February 17, 2017 14:35
Show Gist options
  • Save neilstuartcraig/db025bc6da7e841e8a244b9ec3a75166 to your computer and use it in GitHub Desktop.
Save neilstuartcraig/db025bc6da7e841e8a244b9ec3a75166 to your computer and use it in GitHub Desktop.
nodejs core https POST example - not working code!
// NOTE: This isn't working code, I rehashed it as an example from one of my projects
import https from "https";
const requestOptions =
{
// See https://nodejs.org/api/http.html#http_http_request_options_callback
};
const req = https.request(requestOptions, (res) =>
{
let data = "";
// Configure the handler to fire when response data chunks are received
res.on("data", (d) =>
{
data += d;
});
// Configure the handler to execute when the request is complete
res.on("end", () =>
{
const ret =
{
statusCode: res.statusCode,
body: data
};
return callback(null, ret);
});
});
// Configure the error handler
req.on("error", (e) =>
{
return callback(e, {});
});
// Add the POST data
// NOTE: POSTJSON would be a chunk of JSON data - not shown here
const POSTJSONString = JSON.stringify(POSTJSON);
const HTTPBody = Buffer.from(POSTJSONString, "utf8");
req.write(HTTPBody);
// Make the request
req.end();
@tmaslen
Copy link

tmaslen commented Feb 17, 2017

This almost worked. As I'm posting JSON I had to set the Content-Type in the options object to the right value. In this case...

"headers": {
  "Content-Type": "application/json",
}

Thanks for your help.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment