日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

可用于nodejs的SuperAgent(ajax API)

發布時間:2023/11/27 生活经验 46 豆豆
生活随笔 收集整理的這篇文章主要介紹了 可用于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 方式

  當使用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-typeapplication/x-www-form-urlencoded,多次調用將會通過&來連接,這里的結果為name=tj&pet=tobi:

request.post('/user').send('name=tj').send('pet=tobi').end(callback);

  superagent的請求數據格式化是可以擴展的,不過默認支持formjson兩種格式,想發送數據以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();})

?

轉載于:https://www.cnblogs.com/luoxiaowei/p/6917711.html

總結

以上是生活随笔為你收集整理的可用于nodejs的SuperAgent(ajax API)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。