Skip to content

Instantly share code, notes, and snippets.

@rockymanobi
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rockymanobi/41df2cda5c5034f69c1d to your computer and use it in GitHub Desktop.
Save rockymanobi/41df2cda5c5034f69c1d to your computer and use it in GitHub Desktop.
A wrapper function of "http.request" to execute POST request.
// Wrapper function of "http.request" to execute POST request.
function post( options, queryString, callback ){
var http = require("http"); // should be an argument???
// complete the options
options.headers = options.headers || {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': queryString.length
};
options.method = "POST";
var dataAsString = "";
var req = http.request( options, function(res) {
res.on('data', function(data){ dataAsString += data;} );
res.on('close', function(){ callback( dataAsString ); });
});
req.write( queryString );
req.end();
}
/*
* Sample usage of post function.
* act like following curl command.
* ------------------------------------------------------------------------------------------------
* curl 192.168.0.10:3000/hoges -X "POST" -d "sample_arg=1&sample_arg2=2"
* ------------------------------------------------------------------------------------------------
*/
function postSample(){
var payload = {
sample_arg: "1",
sample_arg2: "2"
};
var queryString =
"sample_arg=" + payload.sample_arg +
"&sample_arg2=" + payload.sample_arg2;
var host = "192.168.0.10";
var port = 3000;
var path = "/hoges";
var options = {
host: host,
port: port,
path: path
};
post( options, queryString, function (chunk) {
console.log('BODY: ' + chunk);
});
}
////////////////////////////////////////////////
// MAIN
////////////////////////////////////////////////
function onInit(){
var wlan = require("CC3000").connect();
var accessPointName = "XXXXXXXXXXXXXX";
var WPA2Key = "NNNNNNNNNNNNNNN";
wlan.connect( accessPointName , WPA2Key , function (s) {
if (s=="dhcp") {
postSample();
}
});
}
onInit();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment