node.js making https post request with x-www-form-urlencoded data
This code snippet is a demo of using node’s https and querystring to make a https post request with data encoded in x-www-form-urlencoded. The querystring module encodes the data in x-www-form-urlencoded and it is then passed in the req.write() to make the https post request. In the reqest headers, the Content-type has to be ‘application/x-www-form-urlencoded’ and the Content-Length has to be the length of the data that’s going to be transmitted in the request.
var https = require('https'); var querystring = require('querystring'); // form data var postData = querystring.stringify({ firstanme: "Amy", lastname: "Li" }); // request option var options = { host: 'example.com', port: 443, method: 'POST', path: '/user', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': postData.length } }; // request object var req = https.request(options, function (res) { var result = ''; res.on('data', function (chunk) { result += chunk; }); res.on('end', function () { console.log(result); }); res.on('error', function (err) { console.log(err); }) }); // req error req.on('error', function (err) { console.log(err); }); //send request witht the postData form req.write(postData); req.end();
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts