簡單示例:
import request from 'superagent';//引用聲明 request.post(api) .withCredentials()//跨域 .end((err, res) => { if (res.ok) { const json = JSON.parse(res.text); } else { console.log('獲取失敗'); } });
1、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){ });
或者傳一個單獨的大對象:
request .get('/search') .query({ query: 'Manny', range: '1..5', order: 'desc' }) .end(function(res){ });
.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){ });
2、post 請求
一個典型的json post請求看起來就像下面的那樣,設置一個合適的Content-type頭字段,然后寫入一些數據,在這個例子里只是json字符串:
request.post('/user')
.set('Content-Type', 'application/json')
.send('{"name":"tj","pet":"tobi"}')
.end(callback)
因為json非常通用,所以就作為默認的Content-type,下面的例子跟上面的一樣:
request.post('/user')
.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的請求數據格式化是可以擴展的,不過默認支持form和json兩種格式,想發送數據以application/x-www-form-urlencoded類型的話,則可以簡單的調用.type()方法傳遞form參數就行,這里默認是json,下面的請求將會postname=tj&pet=tobi內容:
request.post('/user')
.type('form')
.send({ name: 'tj' })
.send({ pet: 'tobi' })
.end(callback)
3、設置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')
4、設置接受類型
跟.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')
5、跨域
.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(); })
