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