美文网首页
SuperAgent 的使用文档

SuperAgent 的使用文档

作者: DontPushMeForev | 来源:发表于2017-07-19 18:35 被阅读0次

    superagent是nodejs里一个非常方便的客户端请求代理模块,当你想处理get,post,put,delete,head请求时,你就应该想起该用它了.

    SuperAgent

    superagent 是一个轻量的,渐进式的ajax api,可读性好,学习曲线低,内部依赖nodejs原生的请求api,适用于nodejs环境下.

    一个简单的post请求,并设置请求头信息的例子

    request

       .post('/api/pet')

        .send({name:'Manny',species:'cat'})

         .set('X-API-Key','foobar')

         .set('Accept','application/json')

          .end(function(res){

              if(res.ok){

                 alert('yay got '+JSON.stringify(res.body));

             }else{

                alert('Oh no! error '+res.text);

            }

    });

    Get请求

    当使用 get 请求传递查询字符串的时候,用 . query()方法,传递一个对象就可以,下面的代码将产生一个 /search?query=Manny&range=1..5&order=desc 的请求

    request 

        .get('/search')

        .query({query:'Manny'})

        .query({range:'1..5'})

        .query({order:'desc'})

        .end(function(res){

     });

    或者传递一个单独的大对象:

    .query({ query: 'Manny', range: '1..5', order: 'desc' })

    也可以达到和上面一样的效果

    .query()方法也允许传递字符串:

    request

    .get('/querystring')

    .query("search=Manny&range=1..5")

    .end(function(res){

     })

    还允许字符串拼接

    request

    .get('/querystring')

    .query("search=Manny”)

    .query(“range=1..5")

    .end(function(res){

    })

    POST/PUT请求

    一个典型的json post请求看起来就像下面的那样,设置一个合适的Content-type头字段,然后写入一些数据,在这个例子里只是json字符串:

    request

    .post('/post地址')

    .set('Content-Type','application/json')//因为json非常通用,所以就作为默认的Content-type,所以这一句不设置也会达到当前的效果

    .send('{"name":"tj","pet":"tobi"}')

    .end(function(res){

    })

    .send()方法可以多次调用

    request

    .post('/post地址')

    .send('{"name":"tj"}')

    .send('{"pet":"tobi"}')

    .end(function(res){

    })

    默认发送字符串,将设置Content-type为application/x-www-form-urlencoded,多次调用将会通过&来连接,这里的结果为name=tj&pet=tobi:

    request

    .post('/post地址')

    .set('Content-Type','application/x-www-form-urlencoded')

    .send('{"name":"tj"}')

    .send('{"pet":"tobi"}')

    .end(function(res){

    })

    superagent的请求数据格式化是可以扩展的,不过默认支持form和json两种格式,想发送数据以application/x-www-form-urlencoded类型的话,则可以简单的调用.type()方法传递form参数就行,这里默认是json,下面的请求将会postname=tj&pet=tobi内容:

    request

    .post('/post地址')

    .type('form')

    .send('{"name":"tj"}')

    .send('{"pet":"tobi"}')

    .end(function(res){

    })

    注意:form是form-data和urlencoded的别名,为了向后兼容

    设置Content-Type

    常见的方案是使用.set()方法

    request.post(“/user”)

    .set('Content-Type', 'application/json')

    一个简便的方法是调用.type()方法,传递一个规范的MIME名称。包括type/subtype,或者一个简单的后缀就像xml,json,png这样,例如:

    request

       .post('/user')

        .type('application/json')

    request

       .post('/user')

        .type('json')

    request

       .post('/user')

    .type('png')

    设置接受类型

    和.type()简便的方法一样,这里也可以调用.accept()方法来设置接受类型,这个值将会被request.types()所引用,支持传递一个规范的MIME名称,包括type/subtype,或者一个简单的后缀就像xml,json,png这样,例如:

    request

       .get('/user')

       .accept('application/json')

    request

      .get('/user')

      .accept('json')

    request

       .get('/user')

       .accept('png')

    解析响应内容

    superagent会解析一些常用的格式给请求者,当前支持application/x-www-form-urlencoded,application/json,multipart/form-data.

    JSON/Urlencoded

    res.body 是解析后的内容对象,比如一个请求响应‘{”user“:{”name“: "tobi"}}’字符串,res.body.user.name 将会返回tobi,同样的,x-www-form-urlencoded格式的user[name]=tobi解析完的值,也是一样的.

    响应属性

    响应一般会提供很多有用的标识以及属性,都在response对象里,按照respone.text,解析后的response.body,头字段,一些标识的顺序来排列.

    Response text

    res.text包含未解析前的响应内容,一般只在mime类型能够匹配text/,json,x-www-form-urlencoding的情况下,默认为nodejs客户端提供,这是为了节省内存.因为当响应以文件或者图片大内容的情况下影响性能.

    Response body

    跟请求数据自动序列化一样,响应数据也会自动的解析,当为一个Content-Type定义一个解析器后,就能自动解析,默认解析包含application/json和application/x-www-form-urlencoded,可以通过访问res.body来访问解析对象.

    Response header fields

    res.header包含解析之后的响应头数据,键值都是node处理成小写字母形式,比如res.header['content-length'].

    Response Content-Type

    Content-Type响应头字段是一个特列,服务器提供res.type来访问它,默认res.charset是空的,如果有的话,则自动填充,例如Content-Type值为text/html; charset=utf8,则res.type为text/html,res.charst为utf8.

    Response status

    响应状态标识可以用来判断请求是否成功,除此之外,可以用superagent来构建理想的restful服务器,这些标识目前定义为:

    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()来定义超时时间,然后当超时错误发生时,为了区别于别的错误,err.timeout属性被定义为超时时间,注意,当超时错误发生后,后续的请求都会被重定向.不是每个请求.

    附加文件

    上面提及的高级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);

    跨域资源共享

    .withCredentials()方法可以激活发送原始cookie的能力,不过只有在Access-Control-Allow-Origin不是一个通配符(*),并且Access-Control-Allow-Credentials为’true’的情况下才行.

    request

       .get('http://localhost:4001/')

       .withCredentials()

        .end(function(res){

            assert(200==res.status);

            assert('tobi'==res.text);

            next();

    })

    更多内容可以参考: https://cnodejs.org/topic/5378720ed6e2d16149fa16bd

    相关文章

      网友评论

          本文标题:SuperAgent 的使用文档

          本文链接:https://www.haomeiwen.com/subject/xbnlkxtx.html