• 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 / 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;

    中止请求

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

    请求超时

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

    request
      .get('/big-file?network=slow')
      .timeout({
        response: 5000,  // Wait 5 seconds for the server to start sending,
        deadline: 60000, // 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(2) 
      .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(200 == 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。

  • 相关阅读:
    BZOJ3473: 字符串
    BZOJ1088: [SCOI2005]扫雷Mine
    跪啃SAM
    BZOJ3932: [CQOI2015]任务查询系统
    BZOJ3545: [ONTAK2010]Peaks
    06.约束
    05.数据表的创建与简单操作
    04.数据库的创建
    安卓6.0后运行时权限封装
    OkGo使用缓存
  • 原文地址:https://www.cnblogs.com/myzy/p/6525416.html
Copyright © 2020-2023  润新知