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']; ... }
相关文章推荐
- HTTP协议处理框架 - 最简单的GET请求拼装和Response解析
- webrequest请求JAVA servlet,webresponse获得返回的压缩后的XML文件,然后再解压处理
- I/O模型和原理,以及简单解析客户端请求WEB服务器内部处理过程,MPM三种模
- 一种异步作业处理请求任务的简单实现(以短信发送为例)
- 【Swift】 GET&POST请求 网络缓存的简单处理
- lighttpd+web.py的一个简单测试结果:每秒可处理350个请求
- IIS服务器处理页面请求的简单过程
- MiniGUI - 简单请求与应答处理
- Ajax响应中文乱码 [SpringMVC使用@ResponseBody处理Ajax请求]
- android(20)(从网络抓取html显示在本地,把流转换成String,请求网络,简单的消息处理机制,编码问题)
- Linux TCP server系列(1)-简单TCP服务器+多进程处理客户请求
- 一款简单实用的请求过滤以及session超时处理
- php学习笔记(三十)ajax请求和接收参数的实现方式(包括json数据格式的简单处理)
- Linux TCP server系列(1)-简单TCP服务器+多进程处理客户请求
- 【转】Ajax响应中文乱码 [SpringMVC使用@ResponseBody处理Ajax请求]
- 使用java 命令运行出现"仅当显式请求注释处理时才接受类名称"的简单处理
- Ajax响应中文乱码 [SpringMVC使用@ResponseBody处理Ajax请求]
- Ajax响应中文乱码 [SpringMVC使用@ResponseBody处理Ajax请求]
- Ajax响应中文乱码 [SpringMVC使用@ResponseBody处理Ajax请求]
- 多个ajax请求下等待条显示和隐藏的简单处理