var request = require('request'); request('http://www.google.com', function (error, response, body) { if (!error && response.statusCode == 200) { console.log(body); } })
var http = require('http') var url = require('url') var request = function(reqUrl, data, cb, headers) { var dataType = typeof data if (dataType == 'function') { headers = cb cb = data rawData = null } else if (dataType == 'object') { rawData = JSON.stringify(data) } else { rawData = data } var urlObj = url.parse(reqUrl) var options = { hostname : urlObj.hostname , port : urlObj.port , path : urlObj.pathname , method : rawData ? 'post' : 'get' } headers && (options.headers = headers) var req = http.request(options, function(res) { var receives = [] if (res.statusCode !== 200) { cb && cb(new Error('Request Failed. Status Code: ' + res.statusCode + ' ' + reqUrl)) return } res.on('data', function(chunk) { receives.push(chunk) }) res.on('end', function() { var resData = Buffer.concat(receives).toString() try { resData = JSON.parse(resData) } catch (e) { } cb && cb(null, res, resData) }) }) req.on('error', function(e) { cb && cb(e) }) rawData && req.write(rawData) req.end() } module.exports = request
request('http://news.sina.com.cn', function(err, res, data) { console.log('geted', data) })
request('http://news.sina.com.cn', function(err, res, data) { console.log('get with cookie', data) }, { cookie: '_sessionid=1234567890' })
对POST的支持
request('http://news.sina.com.cn', { postdata: 'json' }, function(err, res, data) { console.log('get with cookie', data) }, { cookie: '_sessionid=1234567890' })
相关阅读
使用net.socket转发rpc或http request请求 http://ourjs.com/detail/k88hx59pggps
用node.js实现http网页爬虫抓取,模拟ajax\post请求 http://ourjs.com/detail/k881e3m0s7d7
沙发舒服舒服 fsadffsfss
艹