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.
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.
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 .
Node. js has a built-in module called HTTP, which allows Node. js to transfer data over the Hyper Text Transfer Protocol (HTTP).
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With