Axios基本使用

介紹

Axios 是一個基于promise網絡請求庫,作用于node.js和瀏覽器中

特性

  • 從瀏覽器創建 XMLHttpRequests
  • 從 node.js 創建 http 請求
  • 支持 Promise API
  • 攔截請求和響應
  • 轉換請求和響應數據
  • 取消請求
  • 自動轉換JSON數據
  • 客戶端支持防御XSRF

安裝

項目中
npm install axios
yarn add axios
學習階段
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.3.6/axios.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.3.6/axios.min.js"></script>

基本使用

axios({//方法method: "",//urlurl: "",//設置請求體//data: {}
}).then(response => {console.log(response);//...
});

API

axios.request(config)
axios.request({//方法method: "",//urlurl: "",
}).then(response => {console.log(response);//...
});
axios.post(url[, data[, config]])
axios.post("http://....", {"body":"喜大普奔","postId":2
}).then(response => {console.log(response);//...
});
其他
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])

axios返回結果

在這里插入圖片描述
config:為axios配置項,

data:服務器返回的數據,axios默認做json轉換。

headers:http響應頭

request: 原生ajax對象

status:狀態碼

statusText:狀態描述

axios 配置對象

這些是用于發出請求的可用配置選項。

{url: '/user',method: 'get', // defaultbaseURL: 'https://some-domain.com/api/',//對請求數據做預先處理transformRequest: [function (data, headers) {// Do whatever you want to transform the datareturn data;}],//對響應數據進行預處理transformResponse: [function (data) {// Do whatever you want to transform the datareturn data;}],// 請求頭信息配置headers: {'X-Requested-With': 'XMLHttpRequest'},//發送請求時url后邊的參數?id=12345&name=張三params: {ID: 12345,name:"張三"},// `paramsSerializer` is an optional config in charge of serializing `params` 一般用的不多paramsSerializer: {encode?: (param: string): string => { /* Do custom ops here and return transformed string */ }, // custom encoder function; sends Key/Values in an iterative fashionserialize?: (params: Record<string, any>, options?: ParamsSerializerOptions ), // mimic pre 1.x behavior and send entire params object to a custom serializer func. Allows consumer to control how params are serialized.indexes: false // array indexes format (null - no brackets, false (default) - empty brackets, true - brackets with indexes)},//第一種data形式,對象形式data: {firstName: 'Fred'},//第一種data形式,字符串形式data:'Country=Brasil&City=Belo Horizonte',//請求時間timeout: 1000,//跨域請求是否把cookie攜帶過去,false不攜帶withCredentials: false,responseType: 'json', // defaultresponseEncoding: 'utf8', // default// `xsrfCookieName` is the name of the cookie to use as a value for xsrf tokenxsrfCookieName: 'XSRF-TOKEN', // default// `xsrfHeaderName` is the name of the http header that carries the xsrf token valuexsrfHeaderName: 'X-XSRF-TOKEN', // default...//代理,一般用在nodejs里面proxy: {protocol: 'https',host: '127.0.0.1',// hostname: '127.0.0.1' // Takes precedence over 'host' if both are definedport: 9000,auth: {username: 'mikeymike',password: 'rapunz3l'}},...
}

設置默認配置

axios.defaults.method = "get";
axios.defaults.baseURL = "https://api.apiopen.top";
axios.defaults.params = {page: 0,size: 5
}
axios.defaults.timeout = 3000
axios({//urlurl: "/api/getHaoKanVideo"
}).then(response => {console.log(response);
});

創建實例對象發送請求

const a1 = axios.create({baseURL: 'https://some-domain.com/api/',timeout: 1000,headers: {'X-Custom-Header': 'foobar'}
});
const a2 = axios.create({baseURL: 'https://api.apiopen.top',timeout: 1000,headers: {'X-Custom-Header': 'foobar'}
});
//發送請求
a1({url:"xxxx",method:"get"
}).then(response => {console.log(response);
})

當需要請求不同域名發送不同請求時可以創建實例對象去發送請求。

下面列出了可用的實例方法。指定的配置將與實例配置合并。

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])

攔截器

攔截器其實是一些函數,可以在請求和響應之前處理數據、權限判斷等。

//請求攔截器
axios.interceptors.request.use(function (config) {//可以對config進行設置throw ("error")//return config;
}, function (error) {return Promise.reject(error);
});//響應攔截器
axios.interceptors.response.use(function (response) {//可以對response進行處理return response;
}, function (error) {return Promise.reject(error);
});axios({method:"get",url: "http://localhost:3300/api/getHaoKanVideo"
}).then(response => {console.log(response);
});

如果請求攔截器拋出異常,那么響應攔截器執行use中第二個參數回調方法。

請求攔截器執行順序與響應攔截器不同:

axios.interceptors.request.use(function (config) {console.log("請求攔截器-1")return config;
}, function (error) {return Promise.reject(error);
});
axios.interceptors.request.use(function (config) {console.log("請求攔截器-2")return config;
}, function (error) {return Promise.reject(error);
});//響應攔截器
axios.interceptors.response.use(function (response) {console.log("請求攔截器-1")return response;
}, function (error) {return Promise.reject(error);
});
axios.interceptors.response.use(function (response) {console.log("請求攔截器-2")
}, function (error) {return Promise.reject(error);
});axios.defaults.method = "get";
axios.defaults.baseURL = "https://api.apiopen.top";
axios.defaults.params = {page: 0,size: 5
}
axios({//urlurl: "/api/getHaoKanVideo"
}).then(response => {console.log("執行結果-3")console.log(response);
});

執行的結果為:
在這里插入圖片描述
請求攔截器后加入的會先執行。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/90999.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/90999.shtml
英文地址,請注明出處:http://en.pswp.cn/web/90999.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

【大模型LLM】梯度累積(Gradient Accumulation)原理詳解

梯度累積&#xff08;Gradient Accumulation&#xff09;原理詳解 梯度累積是一種在深度學習訓練中常用的技術&#xff0c;特別適用于顯存有限但希望使用較大批量大小&#xff08;batch size&#xff09;的情況。通過梯度累積&#xff0c;可以在不增加單個批次大小的情況下模擬…

阿里云Ubuntu 22.04 ssh隔一段時間自動斷開的解決方法

在使用ssh連接阿里云ubuntu22.04隔一段時間之后就自動斷開&#xff0c;很影響體驗&#xff0c;按照如下配置就可以解決vim /etc/ssh/sshd_config

R中匹配函數

在 R 中&#xff0c;字符串匹配是一個常見的任務&#xff0c;可以使用正則表達式或非正則表達式的方法來完成。以下是對這些方法的總結&#xff0c;包括在向量和數據框中的應用。 正則表達式匹配 常用函數grepl&#xff1a; 功能&#xff1a;檢查向量中的每個元素是否匹配某個正…

Ubuntu服務器上JSP運行緩慢怎么辦?全面排查與優化方案

隨著企業系統越來越多地部署在Linux平臺上&#xff0c;Ubuntu成為JSP Web系統常見的部署環境。但不少開發者會遇到一個共同的問題&#xff1a;在Ubuntu服務器上運行的JSP項目訪問緩慢、頁面加載時間長&#xff0c;甚至出現卡頓現象。這類問題如果不及時解決&#xff0c;容易導致…

web刷題

[極客大挑戰 2019]RCE ME 打開環境&#xff0c;代碼邏輯還是很簡單的 思路是傳參code參數&#xff0c;一般傳參shell然后用蟻劍連接看flag&#xff0c;但是這題做了之后就會發現思路是沒錯但是這題多了一些驗證&#xff0c;這題就是無字符rce&#xff0c;可以考慮用取反&…

FFmpeg+javacpp中FFmpegFrameGrabber

FFmpegjavacpp中FFmpegFrameGrabber1、FFmpegFrameGrabber1.1 Demo使用1.2 音頻相關1.3 視頻相關2、Frame屬性2.1 視頻幀屬性2.2 音頻幀屬性2.3 音頻視頻區分JavaCV 1.5.12 API JavaCPP Presets for FFmpeg 7.1.1-1.5.12 API1、FFmpegFrameGrabber org\bytedeco\javacv\FFmpeg…

1-FPGA的LUT理解

FPGA的LUT理解 FPGA的4輸入LUT中&#xff0c;SRAM存儲的16位二進制數&#xff08;如 0110100110010110&#xff09;直接對應真值表的輸出值。下面通過具體例子詳細解釋其含義&#xff1a; 1. 4輸入LUT 4輸入LUT的本質是一個161的SRAM&#xff0c;它通過存儲真值表的方式實現任意…

Vue2文件上傳相關

導入彈窗<template><el-dialog:title"title":visible.sync"fileUploadVisible"append-to-bodyclose-on-click-modalclose-on-press-escapewidth"420px"><div v-if"showDatePicker">選擇時間&#xff1a;<el-date…

vue使用xlsx庫導出excel

引入xlsx庫 import XLSX from "xlsx";將后端接口返回的數據和列名&#xff0c;拼接到XLSX.utils.aoa_to_sheet中exportExcel() {debugger;if (!this.feedingTableData || this.feedingTableData.length "0") {this.$message.error("投料信息為空&…

卷積神經網絡(CNN)處理流程(簡化版)

前言 是看了這個大佬的視頻后想進行一下自己的整理&#xff08;流程只到了扁平化&#xff09;&#xff0c;如果有問題希望各位大佬能夠給予指正。卷積神經網絡&#xff08;CNN&#xff09;到底卷了啥&#xff1f;8分鐘帶你快速了解&#xff01;_嗶哩嗶哩_bilibilihttps://www.…

DBSyncer:開源免費的全能數據同步工具,多數據源無縫支持!

DBSyncer&#xff08;英[dbs??k??]&#xff0c;美[dbs??k?? 簡稱dbs&#xff09;是一款開源的數據同步中間件&#xff0c;提供MySQL、Oracle、SqlServer、PostgreSQL、Elasticsearch(ES)、Kafka、File、SQL等同步場景。支持上傳插件自定義同步轉換業務&#xff0c;提供…

kafka開啟Kerberos使用方式

kafka SASL_PLAINTEXT serviceName 配置&#xff1a; /etc/security/keytabs/kafka.service.keytab 對應的用戶名 $ cat /home/sunxy/kafka/jaas25.conf KafkaClient { com.sun.security.auth.module.Krb5LoginModule required useKeyTabtrue renewTickettrue serviceName“ocd…

Unity教程(二十四)技能系統 投劍技能(中)技能變種實現

Unity開發2D類銀河惡魔城游戲學習筆記 Unity開發2D類銀河惡魔城游戲學習筆記目錄 技能系統 Unity教程&#xff08;二十一&#xff09;技能系統 基礎部分 Unity教程&#xff08;二十二&#xff09;技能系統 分身技能 Unity教程&#xff08;二十三&#xff09;技能系統 擲劍技能…

局域網TCP通過組播放地址rtp推流和拉流實現實時喊話

應用場景&#xff0c;安卓端局域網不用ip通過組播放地址實現實時對講功能發送端: ffmpeg -f alsa -i hw:1 -acodec aac -ab 64k -ac 2 -ar 16000 -frtp -sdp file stream.sdp rtp://224.0.0.1:14556接收端: ffmpeg -protocol whitelist file,udp,rtp -i stream.sdp -acodec pcm…

基于深度學習的醫學圖像分析:使用YOLOv5實現細胞檢測

最近研學過程中發現了一個巨牛的人工智能學習網站&#xff0c;通俗易懂&#xff0c;風趣幽默&#xff0c;忍不住分享一下給大家。點擊鏈接跳轉到網站人工智能及編程語言學習教程。讀者們可以通過里面的文章詳細了解一下人工智能及其編程等教程和學習方法。下面開始對正文內容的…

32.768KHZ 3215晶振CM315D與NX3215SA應用全場景

在現代電子設備中&#xff0c;一粒米大小的晶振&#xff0c;卻是掌控時間精度的“心臟”。CITIZEN的CM315D系列與NDK的NX3215SA系列晶振便是其中的佼佼者&#xff0c;它們以 3.2 1.5 mm 的小尺寸”(厚度不足1mm)&#xff0c;成為智能設備中隱形的節奏大師。精準計時的奧秘這兩…

嵌軟面試——ARM Cortex-M寄存器組

Cortex-M內存架構包含16個通用寄存器&#xff0c;其中R0-R12是13個32位的通用寄存器&#xff0c;另外三個寄存器是特殊用途&#xff0c;分別是R13&#xff08;棧指針&#xff09;,R14&#xff08;鏈接寄存器&#xff09;,R15&#xff08;程序計數器&#xff09;。對于處理器來說…

7.DRF 過濾、排序、分頁

過濾Filtering 對于列表數據可能需要根據字段進行過濾&#xff0c;我們可以通過添加django-fitlter擴展來增強支持。 pip install django-filter在配置文件中增加過濾器類的全局設置&#xff1a; """drf配置信息必須全部寫在REST_FRAMEWORK配置項中""…

二、CUDA、Pytorch與依賴的工具包

CUDA Compute Unified Device Architecture&#xff08;統一計算架構&#xff09;。專門用于 GPU 通用計算 的平臺 編程接口。CUDA可以使你的程序&#xff08;比如矩陣、神經網絡&#xff09;由 GPU 執行&#xff0c;這比CPU能快幾十甚至上百倍。 PyTorch 是一個深度學習框架…

SpringCloude快速入門

近期簡單了解一下SpringCloude微服務,本文主要就是我學習中所記錄的筆記,然后具體原理可能等以后再來深究,本文可能有些地方用詞不專業還望包容一下,感興趣可以參考官方文檔來深入學習一下微服務,然后我的下一步學習就是docker和linux了。 nacos: Nacos 快速開始 | Nacos 官網…