So I needed to create a monitoring app that would hit a RESTful interface that required authentication. The only way to hit this RESTful service was to POST to a login page and then manage the authentication cookies for the remainder of the session. And I needed to get this done fast.
This is why I love NodeJS. NoneJS is more than a totally awesome web app platform. It makes for a great client application too.
NodeJS for the command line
The following is the basic code for kicking of an https request. The options argument contains the url, method, and any headers (including cookies). The data argument is for any data that needs to be POSTed with the request. (Make sure you set the appropriate headers for the data like content-type).
var cookie = "";
function processRequest(options, data){
var req = https.request(options, function(res) {
res.on('data', function(data) {
cookie = processResponse(data);
});
});
if(data){
//POST data get written here.
//Not included in the options like Jquery
req.write(data);
}
req.end();
req.on('error', function(e) {
console.error(e);
});
}
The magic is in the processResponse function. This is where we capture the cookie and store it for the next request.
function processResponse(){
var cookies = null;
if(res.headers && res.headers["set-cookie"]){
cookies = res.headers["set-cookie"].join(";");
cookies = cookies.replace(/path=\/; HttpOnly;/g, "");
cookies = cookies.replace(/ path=\/; HttpOnly/g, "");
cookies = cookies.trim();
cookies = cookies + " otherCookie=oatmealraisen";'
return cookies;
}
}
Finally we can create the options objects and pass them to the processRequest function.
var loginData = "UserName=XXXXXXXXX&Password=XXXXXXXX&RememberMe=false";
function Login(cookies){
var headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': loginData.length };
var options = { hostname: 'ACME.COM', port: 443, path: '/LogOn', method: 'POST', headers : headers }; return options;
}
function dataSummary(cookies){
var headers = { Cookie: cookies };
var options = { hostname: 'ACME.com', port: 443, path: '/DataSummary', method: 'GET', headers : headers };
return options;
}
processRequest(login());
processRequest(dataSummary(cookie));
NodeJS as a https client. Now the next step is to hook up a send email function. And that is for another blog.