React Native 網(wǎng)絡(luò)請(qǐng)求axios封裝

一個(gè)APP里面少不了網(wǎng)絡(luò)請(qǐng)求,與服務(wù)端進(jìn)行數(shù)據(jù)交互宋舷,
在公司項(xiàng)目中用到了axios這個(gè)組件绪撵,使用很方便,分享下使用情況祝蝠。

axios

Axios 是一個(gè)基于 promise 的 HTTP 庫(kù)音诈,可以用在瀏覽器和 node.js 中。

github地址

特征

  • 從瀏覽器中創(chuàng)建 XMLHttpRequests
  • 從 node.js 創(chuàng)建 http 請(qǐng)求
  • 支持 Promise API
  • 攔截請(qǐng)求和響應(yīng)
  • 轉(zhuǎn)換請(qǐng)求數(shù)據(jù)和響應(yīng)數(shù)據(jù)
  • 取消請(qǐng)求
  • 自動(dòng)轉(zhuǎn)換 JSON 數(shù)據(jù)
  • 客戶(hù)端支持防御 XSRF

安裝

npm install axios

封裝

  • 封裝一個(gè)網(wǎng)絡(luò)請(qǐng)求庫(kù)绎狭,方便項(xiàng)目中統(tǒng)一處理和調(diào)用细溅,新建request.js
import axios from 'axios';

const instance = axios.create({
    baseURL: 'https://some-domain.com/api/',
    timeout: 3000,
    headers: { 'X-Custom-Header': 'foobar' }
});

//請(qǐng)求攔截處理
instance.interceptors.request.use(function (config) {
    // 在發(fā)送請(qǐng)求之前做些什么
    return config;
}, function (error) {
    // 對(duì)請(qǐng)求錯(cuò)誤做些什么
    return Promise.reject(error);
});

//返回?cái)r截處理
instance.interceptors.response.use(function (response) {
    // 對(duì)響應(yīng)數(shù)據(jù)做點(diǎn)什么
    return response;
}, function (error) {
    // 對(duì)響應(yīng)錯(cuò)誤做點(diǎn)什么
    return Promise.reject(error);
});


export const Net = async (api, params) => {
    return new Promise((resolve, reject) => {
        instance.post(api, params)
            .then(res => {
                resolve(res.data)
            })
            .catch(error => {
                reject(error)
            })
    })
}

使用

  • 在需要使用的地方調(diào)用
import {Net} from '../../common/request';

componentDidMount() {
    Net('user/editUser', { userId: '123456', name: 'basil' })
      .then(res => {
        console.log(res);
      })
      .catch(err => {
        console.log(err);
      })
  }

官方示例

  • 執(zhí)行GET請(qǐng)求
const axios = require('axios');

// 請(qǐng)求具有給定ID的用戶(hù)
axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });

// 可選的,上面的請(qǐng)求也可以這樣寫(xiě)
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
  });  

// 使用異步方法
async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

注意:async / await是ECMAScript 2017的一部分儡嘶,在Internet Explorer和舊版瀏覽器中不受支持喇聊,因此請(qǐng)謹(jǐn)慎使用。

  • 執(zhí)行POST請(qǐng)求
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

執(zhí)行多個(gè)并發(fā)請(qǐng)求

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // 這兩個(gè)請(qǐng)求現(xiàn)已完成
  }));
  • axios API
    可以通過(guò)將相關(guān)配置傳遞給axios來(lái)進(jìn)行請(qǐng)求社付。
// 發(fā)送POST請(qǐng)求
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});
// GET請(qǐng)求遠(yuǎn)程圖像
axios({
  method:'get',
  url:'http://bit.ly/2mTM3nY',
  responseType:'stream'
})
  .then(function(response) {
    response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
  });
// 發(fā)送GET請(qǐng)求(默認(rèn)方法)
axios('/user/12345');

請(qǐng)求方法別名

為方便起見(jiàn)承疲,已為所有支持的請(qǐng)求方法提供了別名邻耕。

axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])

使用別名方法時(shí)鸥咖,不需要在config中指定url,method和data屬性兄世。

并發(fā)

Helper函數(shù)用于處理并發(fā)請(qǐng)求啼辣。

axios.all(iterable)
axios.spread(callback)

創(chuàng)建實(shí)例

您可以使用自定義配置創(chuàng)建新的axios實(shí)例。

const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});

實(shí)例方法

下面列出了可用的實(shí)例方法御滩。指定的配置將與實(shí)例配置合并鸥拧。

axios#request(config)
axios#get(url[, config])
axios#delete(url[, config])
axios#head(url[, config])
axios#options(url[, config])
axios#post(url[, data[, config]])
axios#put(url[, data[, config]])
axios#patch(url[, data[, config]])
axios#getUri([config])

請(qǐng)求配置

這些是用于發(fā)出請(qǐng)求的可用配置選項(xiàng)党远。只需要網(wǎng)址。如果未指定方法富弦,請(qǐng)求將默認(rèn)為GET沟娱。

{
  // `url` is the server URL that will be used for the request
  url: '/user',

  // `method` is the request method to be used when making the request
  method: 'get', // default

  // `baseURL` will be prepended to `url` unless `url` is absolute.
  // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
  // to methods of that instance.
  baseURL: 'https://some-domain.com/api/',

  // `transformRequest` allows changes to the request data before it is sent to the server
  // This is only applicable for request methods 'PUT', 'POST', and 'PATCH'
  // The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
  // FormData or Stream
  // You may modify the headers object.
  transformRequest: [function (data, headers) {
    // Do whatever you want to transform the data

    return data;
  }],

  // `transformResponse` allows changes to the response data to be made before
  // it is passed to then/catch
  transformResponse: [function (data) {
    // Do whatever you want to transform the data

    return data;
  }],

  // `headers` are custom headers to be sent
  headers: {'X-Requested-With': 'XMLHttpRequest'},

  // `params` are the URL parameters to be sent with the request
  // Must be a plain object or a URLSearchParams object
  params: {
    ID: 12345
  },

  // `paramsSerializer` is an optional function in charge of serializing `params`
  // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  paramsSerializer: function(params) {
    return Qs.stringify(params, {arrayFormat: 'brackets'})
  },

  // `data` is the data to be sent as the request body
  // Only applicable for request methods 'PUT', 'POST', and 'PATCH'
  // When no `transformRequest` is set, must be of one of the following types:
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - Browser only: FormData, File, Blob
  // - Node only: Stream, Buffer
  data: {
    firstName: 'Fred'
  },

  // `timeout` specifies the number of milliseconds before the request times out.
  // If the request takes longer than `timeout`, the request will be aborted.
  timeout: 1000, // default is `0` (no timeout)

  // `withCredentials` indicates whether or not cross-site Access-Control requests
  // should be made using credentials
  withCredentials: false, // default

  // `adapter` allows custom handling of requests which makes testing easier.
  // Return a promise and supply a valid response (see lib/adapters/README.md).
  adapter: function (config) {
    /* ... */
  },

  // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
  // This will set an `Authorization` header, overwriting any existing
  // `Authorization` custom headers you have set using `headers`.
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },

  // `responseType` indicates the type of data that the server will respond with
  // options are 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
  responseType: 'json', // default

  // `responseEncoding` indicates encoding to use for decoding responses
  // Note: Ignored for `responseType` of 'stream' or client-side requests
  responseEncoding: 'utf8', // default

  // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
  xsrfCookieName: 'XSRF-TOKEN', // default

  // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
  xsrfHeaderName: 'X-XSRF-TOKEN', // default

  // `onUploadProgress` allows handling of progress events for uploads
  onUploadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },

  // `onDownloadProgress` allows handling of progress events for downloads
  onDownloadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },

  // `maxContentLength` defines the max size of the http response content in bytes allowed
  maxContentLength: 2000,

  // `validateStatus` defines whether to resolve or reject the promise for a given
  // HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
  // or `undefined`), the promise will be resolved; otherwise, the promise will be
  // rejected.
  validateStatus: function (status) {
    return status >= 200 && status < 300; // default
  },

  // `maxRedirects` defines the maximum number of redirects to follow in node.js.
  // If set to 0, no redirects will be followed.
  maxRedirects: 5, // default

  // `socketPath` defines a UNIX Socket to be used in node.js.
  // e.g. '/var/run/docker.sock' to send requests to the docker daemon.
  // Only either `socketPath` or `proxy` can be specified.
  // If both are specified, `socketPath` is used.
  socketPath: null, // default

  // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
  // and https requests, respectively, in node.js. This allows options to be added like
  // `keepAlive` that are not enabled by default.
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),

  // 'proxy' defines the hostname and port of the proxy server.
  // You can also define your proxy using the conventional `http_proxy` and
  // `https_proxy` environment variables. If you are using environment variables
  // for your proxy configuration, you can also define a `no_proxy` environment
  // variable as a comma-separated list of domains that should not be proxied.
  // Use `false` to disable proxies, ignoring environment variables.
  // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and
  // supplies credentials.
  // This will set an `Proxy-Authorization` header, overwriting any existing
  // `Proxy-Authorization` custom headers you have set using `headers`.
  proxy: {
    host: '127.0.0.1',
    port: 9000,
    auth: {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },

  // `cancelToken` specifies a cancel token that can be used to cancel the request
  // (see Cancellation section below for details)
  cancelToken: new CancelToken(function (cancel) {
  })
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市腕柜,隨后出現(xiàn)的幾起案子济似,更是在濱河造成了極大的恐慌,老刑警劉巖盏缤,帶你破解...
    沈念sama閱讀 211,194評(píng)論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件砰蠢,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡唉铜,警方通過(guò)查閱死者的電腦和手機(jī)台舱,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,058評(píng)論 2 385
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)潭流,“玉大人竞惋,你說(shuō)我怎么就攤上這事』壹担” “怎么了碰声?”我有些...
    開(kāi)封第一講書(shū)人閱讀 156,780評(píng)論 0 346
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)熬甫。 經(jīng)常有香客問(wèn)我胰挑,道長(zhǎng),這世上最難降的妖魔是什么椿肩? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 56,388評(píng)論 1 283
  • 正文 為了忘掉前任瞻颂,我火速辦了婚禮,結(jié)果婚禮上郑象,老公的妹妹穿的比我還像新娘贡这。我一直安慰自己,他們只是感情好厂榛,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,430評(píng)論 5 384
  • 文/花漫 我一把揭開(kāi)白布盖矫。 她就那樣靜靜地躺著,像睡著了一般击奶。 火紅的嫁衣襯著肌膚如雪辈双。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 49,764評(píng)論 1 290
  • 那天柜砾,我揣著相機(jī)與錄音湃望,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛证芭,可吹牛的內(nèi)容都是我干的瞳浦。 我是一名探鬼主播,決...
    沈念sama閱讀 38,907評(píng)論 3 406
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼废士,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼叫潦!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起官硝,我...
    開(kāi)封第一講書(shū)人閱讀 37,679評(píng)論 0 266
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤诅挑,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后泛源,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體拔妥,經(jīng)...
    沈念sama閱讀 44,122評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,459評(píng)論 2 325
  • 正文 我和宋清朗相戀三年达箍,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了没龙。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,605評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡缎玫,死狀恐怖硬纤,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情赃磨,我是刑警寧澤筝家,帶...
    沈念sama閱讀 34,270評(píng)論 4 329
  • 正文 年R本政府宣布,位于F島的核電站邻辉,受9級(jí)特大地震影響溪王,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜值骇,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,867評(píng)論 3 312
  • 文/蒙蒙 一莹菱、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧吱瘩,春花似錦道伟、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,734評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至票摇,卻和暖如春拘鞋,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背兄朋。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,961評(píng)論 1 265
  • 我被黑心中介騙來(lái)泰國(guó)打工掐禁, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留怜械,地道東北人颅和。 一個(gè)月前我還...
    沈念sama閱讀 46,297評(píng)論 2 360
  • 正文 我出身青樓傅事,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親峡扩。 傳聞我的和親對(duì)象是個(gè)殘疾皇子蹭越,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,472評(píng)論 2 348

推薦閱讀更多精彩內(nèi)容