可用于nodejs的SuperAgent(ajax API)
簡單示例:
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 方式
當(dāng)使用get請求傳遞查詢字符串的時候,用.query()方法,傳遞一個對象就可以,下面的代碼將產(chǎn)生一個/search?query=Manny&range=1..5&order=desc請求:
request.get('/search').query({ query: 'Manny' }).query({ range: '1..5' }).query({ order: 'desc' }).end(function(res){});
或者傳一個單獨(dú)的大對象:
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請求看起來就像下面的那樣,設(shè)置一個合適的Content-type頭字段,然后寫入一些數(shù)據(jù),在這個例子里只是json字符串:
request.post('/user').set('Content-Type', 'application/json').send('{"name":"tj","pet":"tobi"}').end(callback) 因?yàn)閖son非常通用,所以就作為默認(rèn)的Content-type,下面的例子跟上面的一樣:
request.post('/user').send({ name: 'tj', pet: 'tobi' }).end(callback) 或者調(diào)用多次.send()方法:
request.post('/user').send({ name: 'tj' }).send({ pet: 'tobi' }).end(callback) 默認(rèn)發(fā)送字符串,將設(shè)置Content-type為application/x-www-form-urlencoded,多次調(diào)用將會通過&來連接,這里的結(jié)果為name=tj&pet=tobi:
request.post('/user').send('name=tj').send('pet=tobi').end(callback); superagent的請求數(shù)據(jù)格式化是可以擴(kuò)展的,不過默認(rèn)支持form和json兩種格式,想發(fā)送數(shù)據(jù)以application/x-www-form-urlencoded類型的話,則可以簡單的調(diào)用.type()方法傳遞form參數(shù)就行,這里默認(rèn)是json,下面的請求將會postname=tj&pet=tobi內(nèi)容:
request.post('/user').type('form').send({ name: 'tj' }).send({ pet: 'tobi' }).end(callback) 3、設(shè)置content-type
常見的方案是使用.set()方法:
request.post('/user').set('Content-Type', 'application/json') 一個簡便的方法是調(diào)用.type()方法,傳遞一個規(guī)范的MIME名稱,包括type/subtype,或者一個簡單的后綴就像xml,json,png這樣,例如:
request.post('/user').type('application/json')request.post('/user').type('json')request.post('/user').type('png') 4、設(shè)置接受類型
? 跟.type()簡便方法一樣,這里也可以調(diào)用.accept()方法來設(shè)置接受類型,這個值將會被request.types所引用,支持傳遞一個規(guī)范的MIME名稱,包括type/subtype,或者一個簡單的后綴就像xml,json,png這樣,例如:
request.get('/user').accept('application/json')request.get('/user').accept('json')request.get('/user').accept('png') 5、跨域
.withCredentials()方法可以激活發(fā)送原始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();})
?
轉(zhuǎn)載于:https://www.cnblogs.com/luoxiaowei/p/6917711.html
總結(jié)
以上是生活随笔為你收集整理的可用于nodejs的SuperAgent(ajax API)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 我看到自己身上的伤是什么歌?
- 下一篇: hiho 1015 KMP算法 CF