由于决定用couthDB做我的默认数据库,于是用到http.request,但请求死活发不出去
定位到1144行
// require("http").request(options, cb)
function ClientRequest(options, cb) {
var self = this;
OutgoingMessage.call(self);
self.agent = options.agent === undefined ? globalAgent : options.agent;//是否使用代理
var defaultPort = options.defaultPort || 80;
var port = options.port || defaultPort;
var host = options.hostname || options.host || 'localhost';
if (options.setHost === undefined) {
var setHost = true;
}
self.socketPath = options.socketPath;
var method = self.method = (options.method || 'GET').toUpperCase();
self.path = options.path || '/';
if (cb) {
self.once('response', cb);
}
if (!Array.isArray(options.headers)) {
if (options.headers) {
var keys = Object.keys(options.headers);
for (var i = 0, l = keys.length; i
没有结果,这只是一个类,继续
exports.request = function(options, cb) {
if (typeof options === 'string') {
options = url.parse(options);
}
if (options.protocol && options.protocol !== 'http:') {
throw new Error('Protocol:' + options.protocol + ' not supported.');
}
return new ClientRequest(options, cb);
};
exports.get = function(options, cb) {
var req = exports.request(options, cb);
req.end();
return req;
};
发现http.get比http.request唯一要多做的是加了个req.end(),崩溃!
另,此回调果真只有一个参数,即http.createServer(function(req, res) {})的第二个参数一样!
我们只要加个end就可以让程序运行了!(要先安装与启到couthDB)
var http = require('http');
var options = {
port: 5984,
method: 'GET'
};
//这个回调果真只有一个参数,即http.createServer(function(req, res) {})
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
var body = ""
res.on('data', function (chunk) {
body += chunk
});
res.once("end", function(){
var json = JSON.parse(body);
console.log(json)
})
});
req.end()
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});