Changeset 527 for Dev/trunk/src/server/util/request.js
- Timestamp:
- 03/23/14 17:26:12 (11 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
Dev/trunk/src/server/util/request.js
r525 r527 1 1 var HTTPResult = require('./http-result') 2 , request = require('request') 3 , url = require('url') 2 , HTTP = require('http') 3 , HTTPS = require('https') 4 , URL = require('url') 4 5 , _ = require('underscore') 5 6 ; … … 9 10 var result = new HTTPResult(); 10 11 11 options = options ? _.clone(options) : {}; 12 options.uri = url || options.uri; 13 14 request(options,function(err,res,body){ 15 if ( err ) { 16 result.set(-1,err); 17 } else { 18 result.set(res.statusCode,body); 19 } 12 var body = options.body; 13 delete options.body; 14 15 var json = options.json; 16 delete options.json; 17 18 var reqOpts = _.isString(url) ? URL.parse(url) : url; 19 _.extend(reqOpts,options); 20 if ( json === true ) { 21 options.headers = options.headers || {}; 22 _.extend(options.headers,{ 23 'Content-Type': 'application/json', 24 'Accepts': 'application/json' 25 }); 26 } 27 28 var protocol = reqOpts.protocol; 29 var httpModule; 30 if ( protocol === 'http:' ) { 31 httpModule = HTTP; 32 } else if ( protocol === 'https:' ) { 33 httpModule = HTTPS; 34 } else { 35 throw new Error("Unknown protocol "+protocol); 36 } 37 38 var req = httpModule.request(reqOpts); 39 req.on('response', function(response) { 40 var data = ""; 41 response.setEncoding('utf8'); 42 response.on('data', function(chunk) { 43 data += chunk; 44 }); 45 response.on('end', function() { 46 var body; 47 try { 48 if ( json ) { 49 if ( data ) { body = JSON.parse(data); } 50 } else { 51 body = data; 52 } 53 result.set(response.statusCode,body); 54 } catch (ex) { 55 console.log('error',data); 56 result.set(-1,ex); 57 } 58 }); 59 response.on('error', function(error) { 60 result.set(-1,error); 61 }); 20 62 }); 63 req.on('error', function(error){ 64 result.set(-1,error); 65 }); 66 67 if ( body ) { 68 req.write(json ? JSON.stringify(body) : body); 69 } 70 req.end(); 21 71 22 72 return result;
Note: See TracChangeset
for help on using the changeset viewer.