SuperAgent使用简介

SuperAgent使用简介SuperAgentSu 是轻量级更为优化的 ajaxAPI 对比大量糟糕的现存的 API SuperAgent 是灵活的 易读的 并且非常易学 同时 SuperAgent 可用于 Node js request post api pet send name Manny species cat set X API Key

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=

request .head('/users') .query({ email: '' }) .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结构:

--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-- 
 
  • 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]', '') .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版本

在electron中使用浏览器版本

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

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/203071.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月19日 下午10:38
下一篇 2026年3月19日 下午10:39


相关推荐

  • 数据库外键的作用

    数据库外键的作用外键的作用 保持数据一致性 完整性 主要目的是控制存储在外键表中的数据 使两张表形成关联 外键只能引用外表中的列的值 例如 ab 两个表 a 表中存有客户号 客户名称 b 表中存有每个客户的订单有了外键后你只能在确信 b 表中没有客户 x 的订单后 才可以在 a 表中删除客户 x 建立外键的前提 本表的列必须与外键类型相同 外键必须是外表主键

    2026年3月19日
    2
  • 互联网圈内的域名大战[通俗易懂]

    互联网圈内的域名大战[通俗易懂]拥有1亿元人民币,我们可以买下一栋超级豪宅,一件绝世珍品,甚至是一家公司。360为如何花这笔钱提供了新思路:他们以1700万美元的天价,从沃达丰手中拿下了梦寐以求的域名360.com。为得到这颗皇冠上的明珠,360和沃达丰进行了长达3年的反复谈判,他们一度开出了1400万美元的高价却仍被对方拒绝。据说,双方是经过周鸿祎的朋友从中斡旋才以这个“相对优惠”的价码最终成交。域名,对于互联

    2026年4月17日
    4
  • Mysql表分区(diskgenius分区教程)

    Mysql表分区(diskgenius分区教程)一、MySQL分区表介绍分区是一种表的设计模式,正确的分区可以极大地提升数据库的查询效率,完成更高质量的SQL编程。但是如果错误地使用分区,那么分区可能带来毁灭性的的结果。分区功能并不是在存储引擎层完成的,因此不只有InnoDB存储引擎支持分区,常见的存储引擎MyISAM、NDB等都支持分区。但是并不是所有的存储引擎都支持,如CSV、FEDORATED、MERGE等就不支持分区。在

    2022年4月18日
    70
  • Android性能优化思维导图

    Android性能优化思维导图Android 性能优化思维导图

    2026年3月17日
    2
  • RTCM协议解读

    RTCM协议解读RTCM2 x 时代 主要定义了三十多条消息类型协议分析软件 RTCM3 x 时代之后 针对 RTK 多星系 扩展了十几条 协议分析 D3001FEE554C

    2026年3月20日
    2
  • navcat激活码【在线注册码/序列号/破解码】

    navcat激活码【在线注册码/序列号/破解码】,https://javaforall.net/100143.html。详细ieda激活码不妨到全栈程序员必看教程网一起来了解一下吧!

    2022年3月18日
    53

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号