Skip to content

Instantly share code, notes, and snippets.

@coolicer
Created September 9, 2013 06:45
Show Gist options
  • Save coolicer/6492204 to your computer and use it in GitHub Desktop.
Save coolicer/6492204 to your computer and use it in GitHub Desktop.
A api example for node.js http request.
var CG = require('../closure-google');
module.exports = function(app){
app.get('/',function(req,res){
res.render('index', {
title: 'Express',
output: app.get('data') || ''
});
});
app.post('/',function(req,res,next){
var code = req.body.origin_code;
var C = new CG();
C.postCode(code,function(data){
app.set('data', eval('('+ data +')') );
return res.redirect('/');
});
});
}
var querystring = require('querystring');
var http = require('http');
var Transform = function(){
};
Transform.prototype = {
constructor: Transform,
postCode: function(code,cb){
// Build the post string from an object
var post_data = querystring.stringify({
'compilation_level' : 'SIMPLE_OPTIMIZATIONS',
'output_format': 'json',
'output_info': 'compiled_code',
'warning_level' : 'QUIET',
'js_code' : code
});
// An object of options to indicate where to post to
var post_options = {
host: 'closure-compiler.appspot.com',
port: '80',
path: '/compile',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Content-Length': post_data.length
}
};
// Set up the request
var req = http.request(post_options, function(res) {
var datas = '';
res.setEncoding('utf8');
res.on('data', function(chunk){
datas += chunk;
});
res.on('end', function(){
cb(datas);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// post the data
req.write(post_data);
req.end();
}
}
module.exports = Transform;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment