KOA 学习(六)superAgent
原文地址 http://www.2cto.com/kf/201611/569080.html
基本请求
初始化一个请求可以通过调用request模块中适当的方法,然后使用.end()来发送请求,例如一个简单的GET请求:
request
.get('/search')
.end(function(err, res){
});
一个方法字符串也是允许的:
request('GET', '/search').end(callback);
支持ES6,可以使用.then()来代替.end()
request('GET', '/search').then(success, failure);
DELETE, HEAD, POST, PUT以及其他HTTP请求都可使用,只需要简单的改变方法名称:
request
.head('/favicon.ico')
.end(function(err, res){
});
DELETE是特殊的保留字段,方法命名为.del():
request.del('/user/1')
.end(function(err, res){
});
HTTP方法默认为GET,如果你想如此,以下示例是有效的:
request('/search', function(err, res){
});
设置头字段
设置头字段是简单的,使用字段名称和值来调用.set():
request
.get('/search')
.set('API-Key', 'foobar')
.set('Accept', 'application/json')
.end(callback);
你也可以在一个简单请求中通过传递一个对象来设置一些字段:
request
.get('/search')
.set({'API-Key': 'foobar', Accept: 'application/json'})
.end(callback);
GET请求
.query()方法接受对象,当使用GET方法时将生成查询串,以下示例将生成路径/search?query=Manny&range=1..5&order=desc。
request
.get('/search')
.query({ query: 'Manny' })
.query({ range: '1..5' })
.query({ order: 'desc' })
.end(function(err, res){
});
或使用一个简单对象:
request
.get('/search')
.query({ query: 'Manny', range: '1..5', order: 'desc' })
.end(function(err, res){
});
.query()方法也接受字符串:
request
.get('/querystring')
.query('search=Manny&range=1..5')
.end(function(err, res){ });
HEAD请求
你也可以使用.query()方法来进行HEAD请求,以下示例将生成路径/users?email=joe@smith.com
request
.head('/users')
.query({ email: 'joe@smith.com' })
.end(function(err, res){
});
POST/PUT请求
一个典型的JSON POST请求有点像以下示例,我们适当的设置Content-Type头字段,并且”写”一些数据,在此时只是一个JSON字符串
request
.post('/user')
.set('Content-Type', 'application/json')
.send('{"name":"tj","pet":"tobi"}')
.end(callback)
或使用多个.send()请求:
request.post('/user')
.send({ name: 'tj' })
.send({ pet: 'tobi' })
.end(callback)
默认发送字符串将设置Content-Type为application/x-www-form-urlencoded,多个请求将使用&连接,这里结果是name=tj&pet=tobi:
request.post('/user')
.send('name=tj')
.send('pet=tobi')
.end(callback);
SuperAgent格式是可扩展的,但支持默认”json”和”form”,发送类似application/x-www-form-urlencoded的数据只需要调用”form”的.type(),这里默认是”json”,这种请求将会POST”name=tj&pet=tobi”
request.post('/user')
.type('form')
.send({ name: 'tj' })
.send({ pet: 'tobi' })
.end(callback)
设置Content-Type
之前的结论是使用.set()方法
request.post('/user')
.set('Content-Type', 'application/json')
type()方法也可用于速记,接受规范化使用type/subtype完成的MIME类型名称,或简单的扩展名称例如”xml”,”json”,”png”等等:
request.post('/user')
.type('application/json')
request.post('/user')
.type('json')
request.post('/user')
.type('png')
序列化请求结构
SuperAgent会自动序列化JSON和格式,如果你想要再一个传统格式下发送一个有效载荷,你可以使用.serialize()方法替换内置序列化
设置接收
通过速记方法.accept()设置接收头可以达成与.type()方法类似的效果,参考request.types允许你指定类似type/subtype的完全规范化MIME名称,或延期后缀格式类似”xml”、”json”、”png”:
request.get('/user')
.accept('application/json')
request.get('/user')
.accept('json')
request.post('/user')
.accept('png')
查询字符串
res.query(obj)方法可被用于建立一个查询字符串,例如在一个POST中填充?format=json&dest=/login
request
.post('/')
.query({ format: 'json' })
.query({ dest: '/login' })
.send({ post: 'data', here: 'wahoo' })
.end(callback)
解析返回结构
SuperAgent将解析已知的返回结构数据给你,当前支持application/x-www-form-urlencoded,application/json和multipart/form-data.
你可以使用.buffer(true).parse(fn)方法设置自定义解析(提升优先级高于建立解析),如果返回缓冲不可用(.buffer(false)),response事件将发出而不会等待结构解析器结束,因此response.body将不可用
JSON/Urlencoded
res.body属性是解析对象,例如如果一个请求返回JSON字符串’{“user”:{“name”:”tobi”}}’,res.body.user.name将变为”tobi”,同样”user[name]=tobi”的x-www-form-urlencoded值将产生同样的结果
Multipart
Node客户端通过Formidable模块支持multipart/form-data,当解析multipart返回时,对象res.files对你也是可用的,假设例如一个请求响应如下multipart结构:
--whoop
Content-Disposition: attachment; name="image"; filename="tobi.png"
Content-Type: image/png ... data here ...
--whoop
Content-Disposition: form-data; name="name"
Content-Type: text/plain Tobi
--whoop--
res.body.name将为”Tobi”,res.files.image作为一个File对象包含磁盘地址、文件名、和其他属性
响应属性
很多有用的标志和属性设置在Response对象,范围包括返回文本、解析返回结构、头字段、状态标志等
返回文本
res.text属性包含未解析返回结构字符串,这个属性会一直由客户端API提供,并且仅当mime类型匹配”text/”、”/json”或”x-www-form-urlencoded”默认为节点时,这是为了保存记忆,大型结构体的缓存文本,例如multipart文件或图片的效率是非常低的。
强制缓存可查看”缓存返回”部分
返回部分
类似SuperAgent可以自动序列化请求数据,SuperAgent也可以解析它,当一个解析器定义Content-Type,他的解析方式默认包含”application/json”和”application/x-www-form-urlencoded”。解析对象通过res.body可用
返回头字段
res.header包含一个细节头字段的对象,小写字段名如节点一致,例如res.header['content-length']
返回Content-Type
Content-Type返回头是特殊情况,提供res.type,这是字符集的void(如果有的话),例如Content-Type值为”text/html; charset=utf8”将提供res.type值为”text/html”,res.charset属性将包含”utf8”。
返回状态
返回状态标志帮助决定请求是否成功、包含其他有用的信息,使得SuperAgent更理想的与RESTful web服务互动,这些标志当前定义如下:
var type = status / | ; // status / class
res.status = status;
res.statusType = type; // basics
res.info = == type;
res.ok = == type;
res.clientError = == type;
res.serverError = == type;
res.error = == type || == type; // sugar
res.accepted = == status;
res.noContent = == status || == status;
res.badRequest = == status;
res.unauthorized = == status;
res.notAcceptable = == status;
res.notFound = == status;
res.forbidden = == status;
中止请求
中止请求简单调用req.abort()方法
请求超时
通过调用req.timeout(ms)可应用超时,调用之后错误将会触发,为区分其他错误,err.timeout属性设置为ms值。NOTE这是一个超时应用于请求和所有重定向,而不是对应每次请求
request
.get('/big-file?network=slow')
.timeout({
response: , // Wait 5 seconds for the server to start sending,
deadline: , // but allow 1 minute for the file to finish loading.
})
.end(function(err, res){
if (err.timeout) { /* timed out! */ }
});
验证
在所有Node和浏览器通过.auth()方法可用auth:
request
.get('http://local')
.auth('tobi', 'learnboost')
.end(callback);
在Node客户端基础auth可在URL中”user:pass”字段:
request.get('http://tobi:learnboost@local').end(callback);
默认只有 Basic auth可用,在浏览器你可以添加{type:'auto'}来确保所有方法在浏览器(Digest、NTLM等)中建立
request.auth('digest', 'secret', {type:'auto'})
Following重定向
默认超过5个重定向将被followed,但是你可以使用res.redirects(n)方法来指定:
request.get('/some.png')
.redirects()
.end(callback);
Piping数据
Node客户端允许你在请求中pipe传入传出数据,例如piping文件的内容作为请求:
var request = require('superagent')
, fs = require('fs');
var stream = fs.createReadStream('path/to/my.json');
var req = request.post('/somewhere');
req.type('json');
stream.pipe(req);
或piping返回到一个文件:
var request = require('superagent') ,
fs = require('fs');
var stream = fs.createWriteStream('path/to/my.json');
var req = request.get('/some.json');
req.pipe(stream);
Multipart 请求
SuperAgent也适用于建立multipart请求,为此提供了.attach()和.field()方法
附属文件
如上所述,提供了一种更高级别的API,格式为.attach(name, [path], [filename])和.field(name, value)。附属几个文件很简单,你可以提供一个定制文件名作为附属,除非附属文件的基础名已经被使用了
request
.post('/upload')
.attach('avatar', 'path/to/tobi.png', 'user.png')
.attach('image', 'path/to/loki.png')
.attach('file', 'path/to/jane.png')
.end(callback);
字段值
类似HTML中的格式字段,你可以使用.field(name, value)设置字段值,假设你想上传一些图片以及你的名字和email,你的请求可以像下面这样:
request
.post('/upload')
.field('user[name]', 'Tobi')
.field('user[email]', 'tobi@learnboost.com')
.attach('image', 'path/to/tobi.png')
.end(callback);
压缩
node客户端支持压缩返回,最好你不需要做任务事,它本身在工作中
CORS
.withCredentials方法确保可以发送cookies,但仅有当”Access-Control-Allow-Origin”不是通配符时(“*”),”Access-Control-Allow-Credent-ials”为”true”
request
.get('http://localhost:4001/')
.withCredentials()
.end(function(err, res){
assert( == res.status);
assert('tobi' == res.text);
next();
})
错误处理
你的回调函数始终传递两个参数:错误和返回,如果没有错误发送,第一个参数为空:
request
.post('/upload')
.attach('image', 'path/to/tobi.png')
.end(function(err, res){ }); An "error" event is also emitted, with you can listen for: request
.post('/upload')
.attach('image', 'path/to/tobi.png')
.on('error', handle)
.end(function(err, res){ });
Promise and Generator support
SuperAgent的请求是一个”thenable”对象,它兼容JavaScript语法和async/await句法。
类似co或koa可以在任何SuperAgent方法中产生:
var res = yield request
.get('http://local')
.auth('tobi', 'learnboost')
注意SuperAgent期望呈现全局Promise对象,在Internet Explorer或Node.js 0.10中你将需要一个polyfill来使用promises。
KOA 学习(六)superAgent的更多相关文章
- Hbase深入学习(六) Java操作HBase
Hbase深入学习(六) ―― Java操作HBase 本文讲述如何用hbase shell命令和hbase java api对hbase服务器进行操作. 先看以下读取一行记录hbase是如何进行工作 ...
- TweenMax动画库学习(六)
目录 TweenMax动画库学习(一) TweenMax动画库学习(二) TweenMax动画库学习(三) Tw ...
- Koa 学习笔记
开始 就像官网上说的,一切框架都从一个"Hello World"开始,首先我们新建一个 package.json,内容尽量简单: { "name": " ...
- koa 学习资料
koa 学习资料 学习资料 地址 koa 中文版 https://koa.bootcss.com/
- SVG 学习<六> SVG的transform
目录 SVG 学习<一>基础图形及线段 SVG 学习<二>进阶 SVG世界,视野,视窗 stroke属性 svg分组 SVG 学习<三>渐变 SVG 学习<四 ...
- C#多线程学习(六) 互斥对象
如何控制好多个线程相互之间的联系,不产生冲突和重复,这需要用到互斥对象,即:System.Threading 命名空间中的 Mutex 类. 我们可以把Mutex看作一个出租车,乘客看作线程.乘客首先 ...
- Unity学习(六)5.x依赖打包
http://blog.sina.com.cn/s/blog_89d90b7c0102w2ox.html unity5已经封装好了接口,所以依赖打包并没有那么神秘和复杂了. 打包: 1.定义好资源的a ...
- (转)MyBatis框架的学习(六)——MyBatis整合Spring
http://blog.csdn.net/yerenyuan_pku/article/details/71904315 本文将手把手教你如何使用MyBatis整合Spring,这儿,我本人使用的MyB ...
- cesium 学习(六) 坐标转换
cesium 学习(六) 坐标转换 一.前言 在场景中,不管是二维还好还是三维也罢,只要涉及到空间概念都会提到坐标,坐标是让我们理解位置的一个非常有效的东西.有了坐标,我们能很快的确定位置相关关系,但 ...
- day 84 Vue学习六之axios、vuex、脚手架中组件传值
Vue学习六之axios.vuex.脚手架中组件传值 本节目录 一 axios的使用 二 vuex的使用 三 组件传值 四 xxx 五 xxx 六 xxx 七 xxx 八 xxx 一 axios的 ...
随机推荐
- IE6/IE7尿性笔记 && avalon && director
表单提交 [ie6] form默认特性(input回车以及点击type=submit的按钮会自动触发form submit),在ie6中,不能使button[submit],必须是input[subm ...
- 如何使用Python-GnuPG和Python3 实现数据的解密和加密
介绍 GnuPG包提供用于生成和存储加密密钥的完整解决方案.它还允许您加密和签名数据和通信. 在本教程中,您将创建一系列使用Python 3和python-gnupg模块的脚本.这些脚本允许您对多个文 ...
- Requests+Excel接口自动化测试(Python)
一.框架结构: 工程目录 二.Case文件设计 三.基础包 base 3.1 封装get/post请求(runmethon.py) import requests import json class ...
- 金融IT的算法要求
岗位职责 1.负责宏观经济预测的算法研究 2.负责债券.股票.基金等品种的模型研究 3.负责持仓收益分析,及绩效归因等模型研究 任职要求 1.一般数学: 线性代数与矩阵运算 随机过程 微积分 概率论 ...
- (十一)Json文件配置
接上一节,新建一个项目:JsonConfigSample 依然添加Microsoft.AspNetCore.All 在项目下新建一个Class.json配置文件 { ", "Cla ...
- C# IP正则表达式
public static bool IsValidIp(string strIn) { bool b = Regex.IsMatch(strIn, @"^[0-9]{1,3}\.[0-9] ...
- Ubuntu 18.04/18.10快速开启Google BBR的方法
说明:Ubuntu 18.04改变挺大的,内核直接升到了正式版4.15,而BBR内核要求为4.9,也就是说满足了,所以我们不需要换内核就可以很快的开启BBR,这里简单说下方法. 提示:Ubuntu 1 ...
- iOS开发系列-JSON解析
概述 JOSN是一种轻量级的数据格式,一般用于数据交互.服务器返回给客户端,一般都是JSON格式或者XML格式. JSON的格式: {"name" : "CoderHon ...
- java空和非空判断
public static boolean isEmpty(String str){ if("".equals(str)||str==null){ return true; }el ...
- leetcode-95-不同的二叉搜索树②*
题目描述: 方法一:递归 # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self. ...