石家庄网站建设wsjz,海口网站建设策划,网络服务提供者收集和使用,如何规划企业网络推广方案一、http模块提供了两个函数http.request和http.get#xff0c;功能是作为客户端向HTTP服务器发起请求。 Ext.Ajax.request({},function(response))1.http.request(options,callback)发起HTTP请求#xff0c;接受两个参数#xff0c;option是一个类似关联数组的对象#xf… 一、http模块提供了两个函数http.request和http.get功能是作为客户端向HTTP服务器发起请求。
Ext.Ajax.request({},function(response))1.http.request(options,callback)发起HTTP请求接受两个参数option是一个类似关联数组的对象表示请求的参数callback是请求的回调函数option常用的参数如下
host请求网站的域名或IP地址port请求网站的端口默认是80method请求方法模式是GET/POSTpath请求的相对于根的路径默认是/。QueryString应该包含在其中例如/search?querymaricoheaders一个关联数组对象为请求头的内容callback传递一个参数为http.ClientResponse的实例http.request返回一个http.ClientRequest的实例案例clientRequest.jsvar httprequire(http);
var querystringrequire(querystring);
//启动服务
http.createServer(function(req,res){console.log(请求到来解析参数);//解析post请求var post;req.on(data,function(chunk){postchunk;});req.on(end,function(){postquerystring.parse(post);//解析完成console.log(参数解析完成返回name参数);res.end(post.name);});
}).listen(3000);//客户端请求
var contentsquerystring.stringify({name:marico,age:21,address:beijing
});
//Ext.encode();
//声明请求参数
var options{host:localhost,path:/,port:3000,method:POST,headers:{Content-Type:application/x-www-form-urlencoded,Content-Length:contents.length}
};
//发送请求
var reqhttp.request(options,function(res){res.setEncoding(utf-8);res.on(data,function(data){console.log(后台返回数据);console.log(data);})
});
req.write(contents);
//必须调用end()
req.end(); 2.http.get(options,callback) http模块还提供了一个更加简便的方法用于处理GET请求http.get。它是http.request的简化版唯一的区别在于http.get自动将请求方法设为GET请求同时不需要手动调用req.end(); 案例clientGet.js var httprequire(http);
var urlrequire(url);
var utilrequire(util);
//启动服务
http.createServer(function(req,res){console.log(请求到来解析参数);var paramsurl.parse(req.url,true);console.log(解析完成);console.log(util.inspect(params));console.log(向客户端返回);res.end(params.query.name);
}).listen(3000);//客户端请求
var requesthttp.get({host:localhost,path:/user?namemaricoage21,port:3000},function(res){res.setEncoding(utf-8);res.on(data,function(data){console.log( 服务端相应回来的数据为data);})
}); 二、http.ClientRequest
该对象是由http.request或http.get返回产生的对象表示一个已经产生而且正在进行的HTTP请求它提供了response事件即http。request或http.get第二个参数制定的回调函数的绑定对象,请求必须调用end方法结束请求。提供的函数request.abort() 终止正在发送的请求request.setTimeout(timeout,[callback]) 设置请求超时时间timeout为毫秒数当请求超时后callback将会被调用其它request.setNoDelay([noDelay])、request.setScoketKeepAlive([enable],[initialDelay])等函数。API地址http://nodejs.org/api/http.html三、http.ClientResponse
http.ClientReponse是与http.ServerResponse相似提供三个事件data、end和close分别在数据到达传输结束和连接结束时触发其中data事件传递一个参数chunk表示接受到的数据属性表示请求的结果状态statusCode HTTP状态码如200404500httpVersionHTTP协议版本headersHTTP请求头trailersHTTP请求尾函数response.setEncoding([encoding])设置默认的编码当data事件被触发时数据将以encoding编码。默认值为null以buffer的形式存储。response.pause()暂停接受数据和发送事件方便实现下载功能。response.resume()以暂停的状态中恢复