1. 程式人生 > >Node.Js http模組(一)-傳送http請求例項

Node.Js http模組(一)-傳送http請求例項

Node.Js http模組可以建立伺服器應用例項,也能傳送http請求

1.http.get(options[, callback])

傳送簡單Get請求,並響應

var http=require('http');
//get 請求外網
http.get('http://www.gongjuji.net',function(req,res){
	var html='';
	req.on('data',function(data){
		html+=data;
	});
	req.on('end',function(){
		console.info(html);
	});
});
2.http.request(options[, callback])
 // 使用詳細配置,傳送Get或Post請求

傳送Post例項:注http請求頭使用headers指定

var http=require('http');
var querystring=require('querystring');
//傳送 http Post 請求
var postData=querystring.stringify({
	msg:'中文內容'
});
var options={
   hostname:'www.gongjuji.net',
   port:80,
   path:'/',
   method:'POST',
   headers:{
   	//'Content-Type':'application/x-www-form-urlencoded',
   	'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8',
   	'Content-Length':Buffer.byteLength(postData)
   }
}
var req=http.request(options, function(res) {
	console.log('Status:',res.statusCode);
	console.log('headers:',JSON.stringify(res.headers));
	res.setEncoding('utf-8');
	res.on('data',function(chun){
		console.log('body分隔線---------------------------------\r\n');
		console.info(chun);
	});
	res.on('end',function(){
		console.log('No more data in response.********');
	});
});
req.on('error',function(err){
	console.error(err);
});
req.write(postData);
req.end();
傳送Get請求例項:
//傳送Get請求
var http=require('http');
var querystring=require('querystring');
var data={
	age:13,
	time:new Date().getTime()
};
var content=querystring.stringify(data);
var options={
	hostname:'www.gongjuji.net',
	port:80,
	path:'/',
	method:'GET'
}
//建立請求
var req=http.request(options,function(res){
	console.log('STATUS:'+res.statusCode);
	console.log('HEADERS:'+JSON.stringify(res.headers));
	res.setEncoding('utf-8');
	res.on('data',function(chunk){
		console.log('資料片段分隔-----------------------\r\n');
		console.log(chunk);
	});
	res.on('end',function(){
		console.log('響應結束********');
	});
});
req.on('error',function(err){
    console.error(err);
});
req.end();
引數說明:

options can be an object or a string. If options is a string, it is automatically parsed with url.parse().

Options:

  • protocol: Protocol to use. Defaults to 'http:'.
  • host: A domain name or IP address of the server to issue the request to. Defaults to 'localhost'.
  • hostname: Alias for host. To support url.parse() hostname is preferred over host.
  • family: IP address family to use when resolving host and hostname. Valid values are 4 or 6. When unspecified, both IP v4 and v6 will be used.
  • port: Port of remote server. Defaults to 80.
  • localAddress: Local interface to bind for network connections.
  • socketPath: Unix Domain Socket (use one of host:port or socketPath).
  • method: A string specifying the HTTP request method. Defaults to 'GET'.
  • path: Request path. Defaults to '/'. Should include query string if any. E.G. '/index.html?page=12'. An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future.
  • headers: An object containing request headers.
  • auth: Basic authentication i.e. 'user:password' to compute an Authorization header.
  • agent: Controls Agent behavior. When an Agent is used request will default to Connection: keep-alive. Possible values:
    • undefined (default): use http.globalAgent for this host and port.
    • Agent object: explicitly use the passed in Agent.
    • false: opts out of connection pooling with an Agent, defaults request to Connection: close.
更多: