How to record https in Node Js without a third-party module?

I am working on a project that requires https get and post methods. I have 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 is no https.post, and I already tried the http solution here with the https module. How to make an HTTP POST request in node.js? but returns console errors.

I had no problems using get and post with Ajax in my browser with the same api. I can use https.get to send request information, but I don’t think it will be the right way, and I don’t think it will work with sending files later if I decide to expand.

Is there a small example with minimal requirements to do https.request, what will https.post be, if any? I do not want to use npm modules.

+32
source share
1 answer

For example, like this:

 const querystring = require('querystring'); const https = require('https'); var postData = querystring.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(); 
+92
source

Source: https://habr.com/ru/post/1012238/


All Articles