您的位置:首页 > Web前端 > Node.js

Node.js学习笔记(1)---简单response和ruquest请求处理

2016-07-31 15:31 281 查看

1.get请求

可以使用requst对象通过拼接get请求字符串的方式发送get请求:

var request = require('request');
var url = "http://localhost:"+app.get('port')+"/add";
request(url,function(err,response){
JSON.parse(response.body).errCode;
......
});


要使用这样的方式接收response对象传过来的数据,response可以通过以下方式传输数据:

...
res.send({errCode:2,info:"失败"});
...


也可以使用http模块下的方法进行这一过程:

var http=require('http');
...
http.get("http://localhost:"+app.get('port')+"/add?title="+encodeURI(title)+"&info="+encodeURI(info),function (response) {
console.log(response.statusCode);
response.on('data',function (data) {
var s=JSON.parse(data.toString());

});
});


获取response过来的数据时需要执行on方法监听这一事件

2.post请求

发送post的请求时有一种简便的方法,可以使用restler模块

var rest=require('restler');
...
var data={
title : '测试3',
info  : '测试三内容'
};
rest.post('http://localhost:'+app.get('port')+'/add2',{data:data})
.on('complete',function (data) {
console.log(data.errCode);
...
});


通过这样的方式即可完成相应post请求

接收请求参数

必须通过添加监听器的方式来对requset对象传过来的参数进行接收,例如以下方式:

var postdata='';
req.addListener("data",function(postchunk){
postdata += postchunk;
});
req.addListener("end",function(){
var params = query.parse(postdata);
var title=params['title'];
var info=params['info'];
...
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  node-js
相关文章推荐