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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > vue >内容正文

vue

axios,vue-axios在项目中的应用

發布時間:2023/12/20 vue 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 axios,vue-axios在项目中的应用 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Axios 是一個基于 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中

?

關于axios的功能:

1,從瀏覽器中創建XMLHttpRequests

2,從node.js常見Http請求

3,支持Promise API

4,攔截請求和響應

5,轉換請求數據和響應數據

6,取消請求

7,自動轉換JSON數據

8,客戶端支持防御XSRF

?

安裝:

使用node.js自帶的npm:

$ npm install axios

?

如果是vue項目:

$ npm install vue-axios --save

?

vue項目axios配置:

在mian.js中配置如下代碼:

import Vue from 'vue' import axios from 'axios' import VueAxios from 'vue-axios'Vue.use(VueAxios, axios)

?

同也可以直接全局引入cdn:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

?

GET:

?

axios.get('/user?ID=123').then( res => {// 請求數據成功并返回數據 console.info(res)}).catch( err => {if (e.response) {// 請求已發出,服務器返回狀態碼不是 2xx console.info(err.response.data)console.info(err.response.status)console.info(err.response.headers)} else if (err.request) {// 請求已發出,但沒有收到響應// e.request 在瀏覽器里是一個 XMLHttpRequest 實例// 在 node 中是一個 http.ClientRequest 實例 console.info(err.request)} else {// 發送請求時異常,捕獲到錯誤console.info('error', err.message)}console.info(err.config)})?// 等同于以下寫法 axios({url: '/user',methods: 'GET',params: {ID: 123}}).then(res => {console.info(res)}).catch(err => {console.info(err)})???????// 為給定 ID 的 user 創建請求axios.get('/user?ID=12345').then((response)=> {console.log(response);}).catch((error)=> {console.log(error);});?// 可選地,上面的請求可以這樣做axios.get('/user', {params: {ID: 12345}}).then((response)=> {console.log(response);}).catch((error)=> {console.log(error);});

?

?

?

POST:

?

axios.post('/user', {firstName: 'Mike',lastName: 'Allen'}).then(res => {console.info(res)}).catch(err => {console.info(err)})?// 等同于以下寫法 axios({url: '/user',method: 'POST',data: {firstName: 'Mike',lastName: 'Allen'}}).then(res => {console.info(res)}).catch(err => {console.info(err)})??axios.post('/user', {firstName: 'Fred',lastName: 'Flintstone'}).then( (res)=> {console.log(res);}).catch( (err)=> {console.log(err);});

?

?

?

?

執行多個并發請求:

?

function getUserAccount() {return axios.get('/user/12345');}?function getUserPermissions() {return axios.get('/user/12345/permissions');}?axios.all([getUserAccount(), getUserPermission()]).then(axios.spread(function (acct, perms) {// 兩個請求現在都執行完成}));

?

?

?

注意事項:

?

在使用?GET?方法傳遞參數時使用的是?params,并且官方文檔中介紹:

?

params are the URL parameters to be sent with the request. Must be a plain object or a URLSearchParams object.

?

params?作為 URL 鏈接中的參數發送請求,且其必須是一個?plain object?或者是?URLSearchParams object?。

?

  • plain object(純對象):是指?JSON?形式定義的普通對象或者?new Object()?創建的簡單對象;
  • URLSearchParams object:指的是一個可以由?URLSearchParams?接口定義的一些實用方法來處理 URL 的查詢字符串的對象,也就是說?params?傳參是以?/user?ID=1&name=mike&sex=male?形式傳遞的。

?

而在使用?POST?時對應的傳參使用的是?data,data?是作為?請求體?發送的,同樣使用這種形式的還有?PUT、PATCH?等請求方法。有一點需要注意的是,axios?中?POST?的默認請求體類型為?Content-Type:application/json(JSON 規范流行),這也是最常見的請求體類型,也就是說使用的是序列化后的?json?格式字符串來傳遞參數,如:?{ "name" : "mike", "sex" : "male" };同時,后臺必須要以支持?@RequestBody?的形式來接收參數,否則會出現前臺傳參正確,后臺不接收的情況。

?

如果想要設置類型為?Content-Type:application/x-www-form-urlencoded(瀏覽器原生支持),axios?提供了兩種方式,如下:

?

?

?

瀏覽器端

const params = new URLSearchParams();params.append('param1', 'value1');params.append('param2', 'value2');axios.post('/user', params);

不過,并不是所有瀏覽器都支持?URLSearchParams,兼容性查詢caniuse.com,但是這里有一個Polyfill(polyfill:用于實現瀏覽器并不支持的原生 API 的代碼,可以模糊理解為補丁,同時要確保?polyfill?在全局環境中)

?

或者,你也可以用?qs?這個庫來格式化數據,默認情況下在安裝完?axios?后就可以使用?qs庫。

const qs = require('qs');axios.post('/user', qs.stringify({'name': 'mike'}));

?

node 層

在?node?環境中可以使用?querystring?。同樣,也可以使用?qs?來格式化數據。

const querystring = require('querystring');axios.post('http://something.com/', querystring.stringify({'name':'mike'}));

?

axios API

請求方法的別名:

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

在使用別名方法時,url、methods、data?這些屬性都不必在配置中指定

?

?

并發

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

創建實例

axios.create([config])

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

?

實例方法

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

?

請求配置

這些是創建請求時可以使用的配置選項。只有?url?是必需的,如果沒有指定的?method,請求將默認使用?get?方法。

{// `url` 是用于請求的服務器 URLurl: '/user',?// `method` 是創建請求時使用的方法method: 'get', // 默認是 get ?// `baseURL` 將自動加在 `url` 前面,除非 `url` 是一個絕對 URL。// 它可以通過設置一個 `baseURL` 便于為 axios 實例的方法傳遞相對 URLbaseURL: 'https://some-domain.com/api/',?// `transformRequest` 允許在向服務器發送前,修改請求數據// 只能用在 'PUT', 'POST' 和 'PATCH' 這幾個請求方法// 后面數組中的函數必須返回一個字符串,或 ArrayBuffer,或 Stream transformRequest: [function (data) {// 對 data 進行任意轉換處理 ?return data;}],?// `transformResponse` 在傳遞給 then/catch 前,允許修改響應數據 transformResponse: [function (data) {// 對 data 進行任意轉換處理 ?return data;}],?// `headers` 是即將被發送的自定義請求頭headers: {'X-Requested-With': 'XMLHttpRequest'},?// `params` 是即將與請求一起發送的 URL 參數// 必須是一個無格式對象(plain object)或 URLSearchParams 對象params: {ID: 12345},?// `paramsSerializer` 是一個負責 `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` 是作為請求主體被發送的數據// 只適用于這些請求方法 'PUT', 'POST', 和 'PATCH'// 在沒有設置 `transformRequest` 時,必須是以下類型之一:// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams// - 瀏覽器專屬:FormData, File, Blob// - Node 專屬: Stream data: {firstName: 'Fred'},?// `timeout` 指定請求超時的毫秒數(0 表示無超時時間)// 如果請求話費了超過 `timeout` 的時間,請求將被中斷timeout: 1000,?// `withCredentials` 表示跨域請求時是否需要使用憑證withCredentials: false, // 默認的 ?// `adapter` 允許自定義處理請求,以使測試更輕松// 返回一個 promise 并應用一個有效的響應 (查閱 [response docs](#response-api)). adapter: function (config) {/* ... */},?// `auth` 表示應該使用 HTTP 基礎驗證,并提供憑據// 這將設置一個 `Authorization` 頭,覆寫掉現有的任意使用 `headers` 設置的自定義 `Authorization`頭 auth: {username: 'janedoe',password: 's00pers3cret'},?// `responseType` 表示服務器響應的數據類型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'responseType: 'json', // 默認的 ?// `xsrfCookieName` 是用作 xsrf token 的值的cookie的名稱xsrfCookieName: 'XSRF-TOKEN', // default ?// `xsrfHeaderName` 是承載 xsrf token 的值的 HTTP 頭的名稱xsrfHeaderName: 'X-XSRF-TOKEN', // 默認的 ?// `onUploadProgress` 允許為上傳處理進度事件 onUploadProgress: function (progressEvent) {// 對原生進度事件的處理 },?// `onDownloadProgress` 允許為下載處理進度事件 onDownloadProgress: function (progressEvent) {// 對原生進度事件的處理 },?// `maxContentLength` 定義允許的響應內容的最大尺寸maxContentLength: 2000,?// `validateStatus` 定義對于給定的HTTP 響應狀態碼是 resolve 或 reject promise 。如果 `validateStatus` 返回 `true` (或者設置為 `null` 或 `undefined`),promise 將被 resolve; 否則,promise 將被 rejecte validateStatus: function (status) {return status >= 200 && status < 300; // 默認的 },?// `maxRedirects` 定義在 node.js 中 follow 的最大重定向數目// 如果設置為0,將不會 follow 任何重定向maxRedirects: 5, // 默認的 ?// `httpAgent` 和 `httpsAgent` 分別在 node.js 中用于定義在執行 http 和 https 時使用的自定義代理。允許像這樣配置選項:// `keepAlive` 默認沒有啟用httpAgent: new http.Agent({ keepAlive: true }),httpsAgent: new https.Agent({ keepAlive: true }),?// 'proxy' 定義代理服務器的主機名稱和端口// `auth` 表示 HTTP 基礎驗證應當用于連接代理,并提供憑據// 這將會設置一個 `Proxy-Authorization` 頭,覆寫掉已有的通過使用 `header` 設置的自定義 `Proxy-Authorization` 頭。 proxy: {host: '127.0.0.1',port: 9000,auth: : {username: 'mikeymike',password: 'rapunz3l'}},?// `cancelToken` 指定用于取消請求的 cancel token// (查看后面的 Cancellation 這節了解更多)cancelToken: new CancelToken(function (cancel) {})}6 - 響應結構 某個請求的響應包含以下信息:{// `data` 由服務器提供的響應 data: {},?// `status` 來自服務器響應的 HTTP 狀態碼status: 200,?// `statusText` 來自服務器響應的 HTTP 狀態信息statusText: 'OK',?// `headers` 服務器響應的頭 headers: {},?// `config` 是為請求提供的配置信息 config: {}}

使用?then?時,你將接收下面這樣的響應:

axios.get('/user/12345').then(function(response) {console.log(response.data);console.log(response.status);console.log(response.statusText);console.log(response.headers);console.log(response.config);});

在使用?catch?時,或傳遞?rejection callback?作為?then?的第二個參數時,響應可以通過?error?對象可被使用,正如在錯誤處理這一節。

?

全局的 axios 默認值

axios.defaults.baseURL = 'https://api.example.com';axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

?

自定義實例默認值

// 創建實例時設置配置的默認值var instance = axios.create({baseURL: 'https://api.example.com'});?// 在實例已創建后修改默認值instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

?

配置的優先順序

// 使用由庫提供的配置的默認值來創建實例// 此時超時配置的默認值是 `0`var instance = axios.create();?// 覆寫庫的超時默認值// 現在,在超時前,所有請求都會等待 2.5 秒instance.defaults.timeout = 2500;?// 為已知需要花費很長時間的請求覆寫超時設置instance.get('/longRequest', {timeout: 5000});

?

攔截器

在請求或響應被?then?或?catch?處理前攔截它們
// 添加請求攔截器 axios.interceptors.request.use(function (config) {// 在發送請求之前做些什么return config;}, function (error) {// 對請求錯誤做些什么return Promise.reject(error);});?// 添加響應攔截器 axios.interceptors.response.use(function (response) {// 對響應數據做點什么return response;}, function (error) {// 對響應錯誤做點什么return Promise.reject(error);});

如果你想在稍后移除攔截器,可以這樣:

var myInterceptor = axios.interceptors.request.use(function () {/*...*/});axios.interceptors.request.eject(myInterceptor);

可以為自定義 axios 實例添加攔截器:

var instance = axios.create();instance.interceptors.request.use(function () {/*...*/});

?

?

?

轉載于:https://www.cnblogs.com/fengrenfan/p/10740495.html

總結

以上是生活随笔為你收集整理的axios,vue-axios在项目中的应用的全部內容,希望文章能夠幫你解決所遇到的問題。

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