Http request client example (request client) in Node. js, node. jsrequest
Node. JS has a request module that can easily capture webpage content. The simplest example is as follows:
var request = require('request');request('http://www.google.com', function (error, response, body) { if (!error && response.statusCode == 200) { console.log(body); }})
From the above example, we can see that it is very simple to initiate an http request using a request. However, the only problem is that the third-party dependency of the request module is large, it takes several MB of space.
In fact, with the native http module of node. js, you can easily write a similar request function, just a few dozen lines:
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
The interface is the same as the request module. For example, we capture the content of the Sina news homepage.
request('http://news.sina.com.cn', function(err, res, data) { console.log('geted', data)})
It also supports header authentication information, such
request('http://news.sina.com.cn', function(err, res, data) { console.log('get with cookie', data)}, { cookie: '_sessionid=1234567890' })
POST support
request('http://news.sina.com.cn', { postdata: 'json' }, function(err, res, data) { console.log('get with cookie', data)}, { cookie: '_sessionid=1234567890' })
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.