nodejs POST

2020-01-10

Dependency free post in nodejs. Is that a thing? Absolutely!

Posting it here in case, like me, you got annoyed with all the express axiom blabla libraries for this.

Code:
// If you're posting to http you'll need to import from http
const https = require('https'); // Or import, blabla.
const data = JSON.stringify(myobject);
const req = https.request({
host: "example.com",
path: "/where/to/put/it",
// port: 8080,
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(data),
},
}, resp => {
resp.resume()
let data = ""
resp.on("data", chunk => (data += chunk))
resp.on("end", () => {
if (!resp.complete) {
console.error("The connection was terminated while data was still being sent to the server")
} else {
console.log("Data sent! Server response: " + data)
}
})
})

req.on('error', e => console.error(`There was a problem POSTing: ${e.message}`))
req.write(data)
req.end()