Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) {     "use-strict";     https.get(url, function (result) {         var dataQueue = "";             result.on("data", function (dataBuffer) {             dataQueue += dataBuffer;         });         result.on("end", function () {             callback(dataQueue);         });     }); }  get("https://example.com/method", function (data) {     // do something with data }); 

My problem is that there's no https.post 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 https.post if there was one? I don't want to use npm modules.

like image 458
Nova Avatar asked Nov 10 '16 22:11

Nova


People also ask

How do I create an HTTP POST request in node JS?

Example code: var request = require('request') var options = { method: 'post', body: postData, // Javascript object json: true, // Use,If you are sending JSON data url: url, headers: { // Specify headers, If any } } request(options, function (err, res, body) { if (err) { console.

How do I run https in Node?

To start your https server, run node app. js (here, app. js is name of the file) on the terminal. or in your browser, by going to https://localhost:8000 .

Is HTTP a built in Node module?

Node. js has a built-in module called HTTP, which allows Node. js to transfer data over the Hyper Text Transfer Protocol (HTTP).


1 Answers

For example, like this:

const https = require('https');  var postData = JSON.stringify({     'msg' : 'Hello World!' });  var options = {   hostname: 'posttestserver.com',   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) => {     process.stdout.write(d);   }); });  req.on('error', (e) => {   console.error(e); });  req.write(postData); req.end(); 
like image 92
aring Avatar answered Oct 07 '22 13:10

aring