Nova Nova - 11 months ago 59
Node.js Question

How do I make a https post in Node Js without any third party module?

I'm working on a project that requires https get and post methods. I've got a short https.get function working here...

const https = require("https");

function get(url, callback) {
https.get(url, function (result) {
var dataQueue = "";
result.on("data", function (dataBuffer) {
dataQueue += dataBuffer;
result.on("end", function () {

get("", function (data) {
// do something with data

My problem is that there's no and I've already tried the http solution here with https module How to make an HTTP POST request in node.js? but returns console errors.

I've had no problem using get and post with Ajax in my browser to the same api. I can use https.get to send query information but I don't think this would be the correct way and I don't think it will work sending files later if I decide to expand.

Is there a small example, with the minimum requirements, to make a https.request what would be a if there was one? I don't want to use npm modules.

Answer Source

For example, like this:

const querystring = require('querystring');                                                                                                                                                                                                
const https = require('https');

var postData = querystring.stringify({
    'msg' : 'Hello World!'

var options = {
  hostname: '',
  port: 443,
  path: '/post.php',
  method: 'POST',
  headers: {
       'Content-Type': 'application/x-www-form-urlencoded',
       'Content-Length': postData.length

var req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {

req.on('error', (e) => {