source: Dev/trunk/src/server/util/request.js @ 527

Last change on this file since 527 was 527, checked in by hendrikvanantwerpen, 11 years ago
  • Dropped request module for a simple one we wrote ourselves using the native Node modules. Hopefully this one will not suffer from the problem that sometimes empty bodies are returned even when the statuscode and content-length of the request are ok & present.
  • Handle exceptions better in HTTPResult chain, they were hoisted in unknown responses before. Should we not include them in default processing, because they are special?
File size: 1.8 KB
Line 
1var HTTPResult = require('./http-result')
2  , HTTP = require('http')
3  , HTTPS = require('https')
4  , URL = require('url')
5  , _ = require('underscore')
6  ;
7
8module.exports = function(url, options) {
9
10    var result = new HTTPResult();
11   
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        });
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();
71
72    return result;
73   
74};
Note: See TracBrowser for help on using the repository browser.