How do I make a https post in Node Js without any third party module?
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();
Here's a version slightly different from the accepted answer:
async
- You can pass the URL directly (no need to split to hostname, path, port)
- It handles error HTTP status codes
- It handles connection timeouts
- For an alternative content type example, it sends JSON instead of
x-www-form-urlencoded
const https = require('https')
async function post(url, data) {
const dataString = JSON.stringify(data)
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': dataString.length,
},
timeout: 1000, // in ms
}
return new Promise((resolve, reject) => {
const req = https.request(url, options, (res) => {
if (res.statusCode < 200 || res.statusCode > 299) {
return reject(new Error(`HTTP status code ${res.statusCode}`))
}
const body = []
res.on('data', (chunk) => body.push(chunk))
res.on('end', () => {
const resString = Buffer.concat(body).toString()
resolve(resString)
})
})
req.on('error', (err) => {
reject(err)
})
req.on('timeout', () => {
req.destroy()
reject(new Error('Request time out'))
})
req.write(dataString)
req.end()
})
}
const res = await post('https://...', data)