SuperAgent使用简介

来源:互联网 发布:万网域名交易平台 编辑:程序博客网 时间:2024/05/17 07:41

SuperAgent

SuperAgent是轻量级更为优化的ajax API,对比大量糟糕的现存的API,SuperAgent是灵活的、易读的、并且非常易学,同时SuperAgent可用于Node.js!

request   .post('/api/pet')   .send({ name: 'Manny', species: 'cat' })   .set('X-API-Key', 'foobar')   .set('Accept', 'application/json')   .end(function(err, res){     if (err || !res.ok) {       alert('Oh no! error');     } else {       alert('yay got ' + JSON.stringify(res.body));     }   });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

原文地址

http://visionmedia.github.io/superagent/#buffering-responses

测试文档

以下测试文档是使用Mocha的”doc” reporter生成的,并且直接反映测试套件,这提供一种文档的额外资源。

基本请求

初始化一个请求可以通过调用request模块中适当的方法,然后使用.end()来发送请求,例如一个简单的GET请求:

request    .get('/search')    .end(function(err, res){    });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

一个方法字符串也是允许的:

request('GET', '/search').end(callback);
  • 1
  • 1

支持ES6,可以使用.then()来代替.end()

request('GET', '/search').then(success, failure);
  • 1
  • 1

Node客户端也许提供绝对urls:

request    .get('http://example.com/search')    .end(function(err, res){    });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

DELETE, HEAD, POST, PUT以及其他HTTP请求都可使用,只需要简单的改变方法名称:

request   .head('/favicon.ico')   .end(function(err, res){   });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

DELETE是特殊的保留字段,方法命名为.del():

request   .del('/user/1')   .end(function(err, res){   });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

HTTP方法默认为GET,如果你想如此,以下示例是有效的:

request('/search', function(err, res){ });
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

设置头字段

设置头字段是简单的,使用字段名称和值来调用.set():

request   .get('/search')   .set('API-Key', 'foobar')   .set('Accept', 'application/json')   .end(callback);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

你也可以在一个简单请求中通过传递一个对象来设置一些字段:

request    .get('/search')    .set({'API-Key': 'foobar', Accept: 'application/json'})    .end(callback);
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

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){   });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

或使用一个简单对象:

request   .get('/search')   .query({ query: 'Manny', range: '1..5', order: 'desc' })   .end(function(err, res){   });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

.query()方法也接受字符串:

request   .get('/querystring')     .query('search=Manny&range=1..5')   .end(function(err, res){   });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

或连接:

request  .get('/querystring')  .query('search=Manny')  .query('range=1..5')  .end(function(err, res){  });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

HEAD请求

你也可以使用.query()方法来进行HEAD请求,以下示例将生成路径/users?email=joe@smith.com

request   .head('/users')  .query({ email: 'joe@smith.com' })   .end(function(err, res){   });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

POST/PUT请求

一个典型的JSON POST请求有点像以下示例,我们适当的设置Content-Type头字段,并且”写”一些数据,在此时只是一个JSON字符串

request  .post('/user')   .set('Content-Type', 'application/json')   .send('{"name":"tj","pet":"tobi"}')   .end(callback)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

JSON无疑是使用最多的,它也是默认的!以下示例与之前的相同

request  .post('/user')   .send({ name: 'tj', pet: 'tobi' })     .end(callback)
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

或使用多个.send()请求:

request.post('/user')   .send({ name: 'tj' })   .send({ pet: 'tobi' })   .end(callback)
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

默认发送字符串将设置Content-Type为application/x-www-form-urlencoded,多个请求将使用&连接,这里结果是name=tj&pet=tobi

request.post('/user')   .send('name=tj')   .send('pet=tobi')   .end(callback);
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

Note:”form”别名为”form-data”和”urlencoded”并后向相容

设置Content-Type

之前的结论是使用.set()方法

request.post('/user')   .set('Content-Type', 'application/json')
  • 1
  • 2
  • 1
  • 2

.type()方法也可用于速记,接受规范化使用type/subtype完成的MIME类型名称,或简单的扩展名称例如”xml”,”json”,”png”等等:

request.post('/user')   .type('application/json') request.post('/user')   .type('json')request.post('/user')   .type('png')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

序列化请求结构

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')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

查询字符串

res.query(obj)方法可被用于建立一个查询字符串,例如在一个POST中填充?format=json&dest=/login

request   .post('/')   .query({ format: 'json' })   .query({ dest: '/login' })   .send({ post: 'data', here: 'wahoo' })   .end(callback);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

解析返回结构

SuperAgent将解析已知的返回结构数据给你,当前支持application/x-www-form-urlencoded,application/jsonmultipart/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结构:

--whoopContent-Disposition: attachment; name="image"; filename="tobi.png"Content-Type: image/png... data here ...--whoopContent-Disposition: form-data; name="name"Content-Type: text/plainTobi--whoop--
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

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 / 100 | 0; // status / class res.status = status; res.statusType = type; // basics res.info = 1 == type; res.ok = 2 == type; res.clientError = 4 == type; res.serverError = 5 == type; res.error = 4 == type || 5 == type; // sugar res.accepted = 202 == status; res.noContent = 204 == status || 1223 == status; res.badRequest = 400 == status; res.unauthorized = 401 == status; res.notAcceptable = 406 == status; res.notFound = 404 == status; res.forbidden = 403 == status;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

中止请求

中止请求简单调用req.abort()方法

请求超时

通过调用req.timeout(ms)可应用超时,调用之后错误将会触发,为区分其他错误,err.timeout属性设置为ms值。NOTE这是一个超时应用于请求和所有重定向,而不是对应每次请求

验证

在所有Node和浏览器通过.auth()方法可用auth:

request   .get('http://local')   .auth('tobi', 'learnboost')   .end(callback);
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

在Node客户端基础auth可在URL中”user:pass”字段:

request.get('http://tobi:learnboost@local').end(callback);
  • 1
  • 1

默认只有Basicauth可用,在浏览器你可以添加{type:'auto'}来确保所有方法在浏览器(Digest、NTLM等)中建立

request.auth('digest', 'secret', {type:'auto'})
  • 1
  • 1

Following重定向

默认超过5个重定向将被followed,但是你可以使用res.redirects(n)方法来指定:

request   .get('/some.png')   .redirects(2)   .end(callback);
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

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);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

或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);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

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);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

字段值

类似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);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

压缩

node客户端支持压缩返回,最好你不需要做任务事,它本身在工作中

缓冲返回

为了强制返回结构缓冲为res.text,你可以调用req.buffer(),你可以调用req.buffer(false)来撤销默认缓存文本返回,例如”text/plain”,”text/html”等。 
res.buffered标志缓存已提供,你可以使用这个来处理在相同回调中的缓存或未缓存返回

CORS

.withCredentials方法确保可以发送cookies,但仅有当”Access-Control-Allow-Origin”不是通配符时(“*”),”Access-Control-Allow-Credent-ials”为”true”

request   .get('http://localhost:4001/')   .withCredentials()   .end(function(err, res){     assert(200 == res.status);     assert('tobi' == res.text);     next();   })
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

错误处理

你的回调函数始终传递两个参数:错误和返回,如果没有错误发送,第一个参数为空:

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){   });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

注意4xx或5xx的超级代理返回默认为错误,例如你获取一个500或403返回,使用err.status可使用这个状态信息,这种返回错误页包含了一个err.response字段,它有着”Response properties”中所有的上述状态。 
网络失败,超时,和其他错误产生无返回将不包含err.statuserr.response字段。 
如果你处理404或其他HTTP错误返回,你可以查询err.status属性,当一个HTTP错误发生(4xx或5xx返回),res.error属性石一个Error对象,这允许你像这样执行检查:

if (err && err.status === 404) {   alert('oh no ' + res.body.message);}else if (err) {   // all other error types we handle generically}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

Promise and Generator support

SuperAgent的请求是一个”thenable”对象,它兼容JavaScript语法和async/await句法。 
类似co或koa可以在任何SuperAgent方法中产生:

var res = yield request   .get('http://local')   .auth('tobi', 'learnboost')
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

注意SuperAgent期望呈现全局Promise对象,在Internet Explorer或node.js 0.10中你将需要一个polyfill来使用promises。

Facebook和接受JSON

如果你请求了Facebook的API,确保在你的请求中发送一个Accept: application/json头,如果你不想这样做,Facebook会返回Content-Type: text/javascript: charset=UTF-8,SuperAgent将不会解析并且res.body将不会定义,你可以使用req.accept('json')req.header('Accept', 'application/json')

浏览器和node版本

SuperAgent有两个实现:一个给浏览器(使用XHR),一个给Node.JS(使用核心http模板),默认Browserity和WebPack将采用浏览器版本 
如果你想要使用WebPack来编译Node.JS代码,你必须在它的配置中指定node目标

在electron中使用浏览器版本

Electron开发者报告如果你使用SuperAgent的浏览器版本而不是Node版本时,你可以require('superagent/superagent'),你的请求将不会在Chrome开发者工具中表现出来,注意这个环境不被自动化测试包含斌并且不是正式支持的

1 0
原创粉丝点击