Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.