Created
February 21, 2021 21:49
-
-
Save pongo/ab861ab5dacb970752e4223141ff7acc to your computer and use it in GitHub Desktop.
POST request via plain node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const http = require('http'); | |
var querystring = require('querystring'); | |
const { performance } = require('perf_hooks'); | |
const t1 = performance.now(); | |
var post_data = querystring.stringify({}); | |
// An object of options to indicate where to post to | |
var post_options = { | |
host: 'localhost', | |
port: '3000', | |
path: '/', | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/json;charset=utf-8', | |
'Content-Length': Buffer.byteLength(post_data), | |
}, | |
}; | |
const post_req = http | |
.request(post_options, (resp) => { | |
resp.setEncoding('utf8'); | |
let data = ''; | |
// A chunk of data has been received. | |
resp.on('data', (chunk) => { | |
data += chunk; | |
}); | |
resp.on('end', () => { | |
const t2 = performance.now(); | |
console.log('duration', t2 - t1); | |
console.log('on end', data); | |
}); | |
}) | |
.on('error', (err) => { | |
console.log('Error: ' + err.message); | |
}); | |
post_req.write(post_data); | |
post_req.end(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment