Axios?get?post請(qǐng)求傳遞參數(shù)的實(shí)現(xiàn)代碼
Axios概述
首先,axios是基于promise用于瀏覽器和node.js的http客戶端
特點(diǎn) :
支持瀏覽器和node.js
支持promise
能攔截請(qǐng)求和響應(yīng)
能轉(zhuǎn)換請(qǐng)求和響應(yīng)數(shù)據(jù)
能取消請(qǐng)求
自動(dòng)轉(zhuǎn)換json數(shù)據(jù)
瀏覽器端支持防止CSRF(跨站請(qǐng)求偽造)
一、 安裝
npm安裝
$ npm install axios
bower安裝
$ bower install axios
通過cdn引入
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
首先需要安裝axios
下一步,在main.js中引入axios
import axios from "axios";
與很多第三方模塊不同的是,axios不能使用use方法,由于axios比vue出來的早 所以需要放到vue的原型對(duì)象中
Vue.prototype.$axios = axios;
接著,我們就可以在App.vue中使用axios了
created:function(){ this.$axios.get("/seller",{"id":123}).then(res=>{ console.log(res.data); }); }
1.發(fā)起一個(gè)get請(qǐng)求
<input id="get01Id" type="button" value="get01"/> <script> $("#get01Id").click(function () { axios.get('http://localhost:8080/user/findById?id=1') .then(function (value) { console.log(value); }) .catch(function (reason) { console.log(reason); }) }) </script>
另外一種形式:
<input id="get02Id" type="button" value="get02"/> <script> $("#get02Id").click(function () { axios.get('http://localhost:8080/user/findById', { params: { id: 1 } }) .then(function (value) { console.log(value); }) .catch(function (reason) { console.log(reason); }) }) </script>
2.發(fā)起一個(gè)post請(qǐng)求
在官方文檔上面是這樣的:
axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }).then(function (res) { console.log(res); }).catch(function (err) { console.log(err); });
但是如果這么寫,會(huì)導(dǎo)致后端接收不到數(shù)據(jù)
所以當(dāng)我們使用post請(qǐng)求的時(shí)候,傳遞參數(shù)要這么寫:
<input id="post01Id" type="button" value="post01"/> <script> $("#post01Id").click(function () { var params = new URLSearchParams(); params.append('username', 'sertyu'); params.append('password', 'dfghjd'); axios.post('http://localhost:8080/user/addUser1', params) .then(function (value) { console.log(value); }) .catch(function (reason) { console.log(reason); }); }) </script>
3.執(zhí)行多個(gè)并發(fā)請(qǐng)求
<input id="button01Id" type="button" value="點(diǎn)01"/> <script> function getUser1() { return axios.get('http://localhost:8080/user/findById?id=1'); } ? function getUser2() { return axios.get('http://localhost:8080/user/findById?id=2'); } ? $("#buttonId").click(function () { axios.all([getUser1(), getUser2()]) .then(axios.spread(function (user1, user2) { alert(user1.data.username); alert(user2.data.username); })) }) </script>
另外一種形式:
<input id="button02Id" type="button" value="點(diǎn)02"/> <script> $("#button02Id").click(function () { axios.all([ axios.get('http://localhost:8080/user/findById?id=1'), axios.get('http://localhost:8080/user/findById?id=2') ]) .then(axios.spread(function (user1, user2) { alert(user1.data.username); alert(user2.data.username); })) }) </script>
當(dāng)所有的請(qǐng)求都完成后,會(huì)收到一個(gè)數(shù)組,包含著響應(yīng)對(duì)象,其中的順序和請(qǐng)求發(fā)送的順序相同,可以使用axios.spread分割成多個(gè)單獨(dú)的響應(yīng)對(duì)象
三、 axiosAPI
(一)可以通過向axios傳遞相關(guān)配置來創(chuàng)建請(qǐng)求
axios(config)
<input id="buttonId" type="button" value="點(diǎn)"/> <script> $("#buttonId").click(function () { var params = new URLSearchParams(); params.append('username','trewwe'); params.append('password','wertyu'); // 發(fā)起一個(gè)post請(qǐng)求 axios({ method:'post', url:'http://localhost:8080/user/addUser1', data:params }); }) </script>
axios(url[,config])
<input id="buttonId" type="button" value="點(diǎn)"/> <script> $("#buttonId").click(function () { // 發(fā)起一個(gè)get請(qǐng)求,(get是默認(rèn)的請(qǐng)求方法) axios('http://localhost:8080/user/getWord'); }) </script>
(二)請(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í),url、method、data這些屬性都不必在配置中指定
(三)并發(fā)請(qǐng)求,即是幫助處理并發(fā)請(qǐng)求的輔助函數(shù)
//iterable是一個(gè)可以迭代的參數(shù)如數(shù)組等 axios.all(iterable) //callback要等到所有請(qǐng)求都完成才會(huì)執(zhí)行 axios.spread(callback)
(四)創(chuàng)建實(shí)例,使用自定義配置
1.axios.create([config])
var instance = axios.create({ baseURL:"http://localhost:8080/user/getWord", timeout:1000, headers: {'X-Custom-Header':'foobar'} });
2.實(shí)例的方法
以下是實(shí)例方法,注意已經(jīng)定義的配置將和利用create創(chuàng)建的實(shí)例的配置合并
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]])
四、請(qǐng)求配置
請(qǐng)求的配置選項(xiàng),只有url選項(xiàng)是必須的,如果method選項(xiàng)未定義,那么它默認(rèn)是以get方式發(fā)出請(qǐng)求
{ // url 是用于請(qǐng)求的服務(wù)器 URL url: '/user/getWord', ? // method 是創(chuàng)建請(qǐng)求時(shí)使用的方法 method: 'get', // 默認(rèn)是 get ? // baseURL 將自動(dòng)加在 url 前面,除非 url 是一個(gè)絕對(duì)路徑。 // 它可以通過設(shè)置一個(gè) baseURL 便于為 axios 實(shí)例的方法傳遞相對(duì)路徑 baseURL: 'http://localhost:8080/', ? // transformRequest 允許在向服務(wù)器發(fā)送前,修改請(qǐng)求數(shù)據(jù) // 只能用在 'PUT', 'POST' 和 'PATCH' 這幾個(gè)請(qǐng)求方法 // 后面數(shù)組中的函數(shù)必須返回一個(gè)字符串,或 ArrayBuffer,或 Stream transformRequest: [function (data) { // 對(duì) data 進(jìn)行任意轉(zhuǎn)換處理 ? return data; }], ? // transformResponse 在傳遞給 then/catch 前,允許修改響應(yīng)數(shù)據(jù) transformResponse: [function (data) { // 對(duì) data 進(jìn)行任意轉(zhuǎn)換處理 ? return data; }], ? // headers 是即將被發(fā)送的自定義請(qǐng)求頭 headers: {'X-Requested-With': 'XMLHttpRequest'}, ? // params 是即將與請(qǐng)求一起發(fā)送的 URL 參數(shù) // 必須是一個(gè)無格式對(duì)象(plain object)或 URLSearchParams 對(duì)象 params: { ID: 12345 }, ? // paramsSerializer 是一個(gè)負(fù)責(zé) params 序列化的函數(shù) // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/) paramsSerializer: function (params) { return Qs.stringify(params, {arrayFormat: 'brackets'}) }, ? // data 是作為請(qǐng)求主體被發(fā)送的數(shù)據(jù) // 只適用于這些請(qǐng)求方法 'PUT', 'POST', 和 'PATCH' // 在沒有設(shè)置 transformRequest 時(shí),必須是以下類型之一: // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - 瀏覽器專屬:FormData, File, Blob // - Node 專屬: Stream data: { firstName: 'yuyao' }, ? // timeout 指定請(qǐng)求超時(shí)的毫秒數(shù)(0 表示無超時(shí)時(shí)間) // 如果請(qǐng)求話費(fèi)了超過 timeout 的時(shí)間,請(qǐng)求將被中斷 timeout: 1000, ? // withCredentials 表示跨域請(qǐng)求時(shí)是否需要使用憑證 withCredentials: false, // 默認(rèn)的 ? // adapter 允許自定義處理請(qǐng)求,以使測(cè)試更輕松 // 返回一個(gè) promise 并應(yīng)用一個(gè)有效的響應(yīng) (查閱 [response docs](#response-api)). adapter: function (config) { /* ... */ }, ? // auth 表示應(yīng)該使用 HTTP 基礎(chǔ)驗(yàn)證,并提供憑據(jù) // 這將設(shè)置一個(gè) Authorization 頭,覆寫掉現(xiàn)有的任意使用 headers 設(shè)置的自定義 Authorization 頭 auth: { username: 'zhangsan', password: '12345' }, ? // responseType 表示服務(wù)器響應(yīng)的數(shù)據(jù)類型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream' responseType: 'json', // 默認(rèn)的 ? // xsrfCookieName 是用作 xsrf token 的值的cookie的名稱 xsrfCookieName: 'XSRF-TOKEN', // default ? // xsrfHeaderName 是承載 xsrf token 的值的 HTTP 頭的名稱 xsrfHeaderName: 'X-XSRF-TOKEN', // 默認(rèn)的 ? // onUploadProgress 允許為上傳處理進(jìn)度事件 onUploadProgress: function (progressEvent) { // 對(duì)原生進(jìn)度事件的處理 }, ? // onDownloadProgress 允許為下載處理進(jìn)度事件 onDownloadProgress: function (progressEvent) { // 對(duì)原生進(jìn)度事件的處理 }, ? // maxContentLength 定義允許的響應(yīng)內(nèi)容的最大尺寸 maxContentLength: 2000, ? // validateStatus 定義對(duì)于給定的HTTP 響應(yīng)狀態(tài)碼是 resolve 或 reject promise 。 // 如果 validateStatus 返回 true (或者設(shè)置為 null 或 undefined ),promise 將被 resolve; 否則,promise 將被 rejecte validateStatus: function (status) { return status >= 200 && status < 300; // 默認(rèn)的 }, ? // maxRedirects 定義在 node.js 中 follow 的最大重定向數(shù)目 // 如果設(shè)置為0,將不會(huì) follow 任何重定向 maxRedirects: 5, // 默認(rèn)的 ? // httpAgent 和 httpsAgent 分別在 node.js 中用于定義在執(zhí)行 http 和 https 時(shí)使用的自定義代理。允許像這樣配置選項(xiàng): // keepAlive 默認(rèn)沒有啟用 httpAgent: new http.Agent({keepAlive: true}), httpsAgent: new https.Agent({keepAlive: true}), ? // 'proxy' 定義代理服務(wù)器的主機(jī)名稱和端口 // auth 表示 HTTP 基礎(chǔ)驗(yàn)證應(yīng)當(dāng)用于連接代理,并提供憑據(jù) // 這將會(huì)設(shè)置一個(gè) Proxy-Authorization 頭,覆寫掉已有的通過使用 header 設(shè)置的自定義 Proxy-Authorization 頭。 proxy: { host: '127.0.0.1', port: 9000, auth: { username: 'lisi', password: '54321' } }, ? // cancelToken 指定用于取消請(qǐng)求的 cancel token cancelToken: new CancelToken(function (cancel) { }) }
五、響應(yīng)內(nèi)容
{ data:{}, status:200, //從服務(wù)器返回的http狀態(tài)文本 statusText:'OK', //響應(yīng)頭信息 headers: {}, //config是在請(qǐng)求的時(shí)候的一些配置信息 config: {} }
可以這樣來獲取響應(yīng)信息
<input id="getId" type="button" value="get"/> <script> $("#getId").click(function () { axios.get('http://localhost:8080/user/findById?id=1') .then(function (value) { console.log("data:"+value.data); console.log("status:"+value.status); console.log("statusText:"+value.statusText); console.log("headers:"+value.headers); console.log("config:"+value.config); }) .catch(function (reason) { console.log(reason); }) }) </script>
六、默認(rèn)配置
默認(rèn)配置對(duì)所有請(qǐng)求都有效
1、全局默認(rèn)配置
axios.defaults.baseURL = 'http://localhost:8080/'; axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; axios.defaults.headers.post['content-Type'] = 'appliction/x-www-form-urlencoded';
2、自定義的實(shí)例默認(rèn)設(shè)置
//當(dāng)創(chuàng)建實(shí)例的時(shí)候配置默認(rèn)配置 var instance = axios.create({ baseURL: 'http://localhost:8080/' }); //當(dāng)實(shí)例創(chuàng)建時(shí)候修改配置 instance.defaults.headers.common["Authorization"] = AUTH_TOKEN;
3、配置中有優(yōu)先級(jí)
config配置將會(huì)以優(yōu)先級(jí)別來合并,順序是lib/defauts.js中的默認(rèn)配置,然后是實(shí)例中的默認(rèn)配置,最后是請(qǐng)求中的config參數(shù)的配置,越往后等級(jí)越高,后面的會(huì)覆蓋前面的例子。
//創(chuàng)建一個(gè)實(shí)例的時(shí)候會(huì)使用libray目錄中的默認(rèn)配置 //在這里timeout配置的值為0,來自于libray的默認(rèn)值 var instance = axios.create(); //回覆蓋掉library的默認(rèn)值 //現(xiàn)在所有的請(qǐng)求都要等2.5S之后才會(huì)發(fā)出 instance.defaults.timeout = 2500; //這里的timeout回覆蓋之前的2.5S變成5s instance.get('/longRequest',{ timeout: 5000 });
七、攔截器
1.可以在請(qǐng)求、響應(yīng)在到達(dá)then/catch之前攔截
//添加一個(gè)請(qǐng)求攔截器 axios.interceptors.request.use(function(config){ //在請(qǐng)求發(fā)出之前進(jìn)行一些操作 return config; },function(err){ //Do something with request error return Promise.reject(error); }); //添加一個(gè)響應(yīng)攔截器 axios.interceptors.response.use(function(res){ //在這里對(duì)返回的數(shù)據(jù)進(jìn)行處理 return res; },function(err){ //Do something with response error return Promise.reject(error); })
2.取消攔截器
var myInterceptor = axios.interceptor.request.use(function(){/*....*/}); axios.interceptors.request.eject(myInterceptor);
3.給自定義的axios實(shí)例添加攔截器
var instance = axios.create(); instance.interceptors.request.use(function(){})
八、錯(cuò)誤處理
<input id="getId" type="button" value="get"/> <script> $("#getId").click(function () { axios.get('http://localhost:8080/user/findById?id=100') .catch(function (error) { if (error.response) { //請(qǐng)求已經(jīng)發(fā)出,但是服務(wù)器響應(yīng)返回的狀態(tài)嗎不在2xx的范圍內(nèi) console.log("data:"+error.response.data); console.log("status:"+error.response.status); console.log("header:"+error.response.header); } else { //一些錯(cuò)誤是在設(shè)置請(qǐng)求的時(shí)候觸發(fā) console.log('Error', error.message); } console.log(error.config); }); }) </script>
九、取消
通過一個(gè)cancel token來取消一個(gè)請(qǐng)求
通過CancelToken.source工廠函數(shù)來創(chuàng)建一個(gè)cancel token
<input id="getId" type="button" value="get"/> <input id="unGetId" type="button" value="unGet"/> <script> var CancelToken = axios.CancelToken; var source = CancelToken.source(); $("#getId").click(function () { axios.get('http://localhost:8080/user/findById?id=1', { cancelToken: source.token }) .then(function (value) { console.log(value); }) .catch(function (thrown) { if (axios.isCancel(thrown)) { console.log('Request canceled', thrown.message); } else { //handle error } }); }); $("#unGetId").click(function () { //取消請(qǐng)求(信息的參數(shù)可以設(shè)置的) source.cancel("操作被用戶取消"); }); </script>
到此這篇關(guān)于axios get post請(qǐng)求 傳遞參數(shù)的文章就介紹到這了,更多相關(guān)axios get post請(qǐng)求 傳遞參數(shù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- vue3實(shí)戰(zhàn)-axios請(qǐng)求封裝問題(get、post、put、delete)
- react中axios結(jié)合后端實(shí)現(xiàn)GET和POST請(qǐng)求方式
- vue如何封裝Axios的get、post請(qǐng)求
- axios?gin的GET和POST請(qǐng)求實(shí)現(xiàn)示例
- Vue axios全局?jǐn)r截 get請(qǐng)求、post請(qǐng)求、配置請(qǐng)求的實(shí)例代碼
- vue axios數(shù)據(jù)請(qǐng)求get、post方法及實(shí)例詳解
- vue中axios處理http發(fā)送請(qǐng)求的示例(Post和get)
- vue中axios的get請(qǐng)求和post請(qǐng)求的傳參方式、攔截器示例代碼
相關(guān)文章
JS實(shí)現(xiàn)基本的網(wǎng)頁計(jì)算器功能示例
這篇文章主要介紹了JS實(shí)現(xiàn)基本的網(wǎng)頁計(jì)算器功能,涉及JavaScript事件響應(yīng)及數(shù)值運(yùn)算相關(guān)操作技巧,需要的朋友可以參考下2020-01-01JS實(shí)現(xiàn)全屏預(yù)覽F11功能的示例代碼
這篇文章主要介紹了JS實(shí)現(xiàn)全屏預(yù)覽F11功能的示例代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-07-07詳解微信小程序開發(fā)—你期待的分享功能來了,微信小程序序新增5大功能
微信小程序在12月21日發(fā)布了新版本的開發(fā)工具,并在官網(wǎng)公布新增分享、模板消息、客服消息、掃一掃、帶參數(shù)二維碼功能。2016-12-12微信小程序 仿美團(tuán)分類菜單 swiper分類菜單
本文主要介紹了微信小程序仿美團(tuán)分類菜單(swiper分類菜單)的相關(guān)知識(shí)。具有很好的參考價(jià)值。下面跟著小編一起來看下吧2017-04-04每天一篇javascript學(xué)習(xí)小結(jié)(Boolean對(duì)象)
這篇文章主要介紹了javascript中的Boolean對(duì)象知識(shí)點(diǎn),對(duì)Boolean對(duì)象的基本使用方法進(jìn)行解釋,一段很詳細(xì)的代碼介紹,感興趣的小伙伴們可以參考一下2015-11-11javascript閉包的高級(jí)使用方法實(shí)例
這篇文章介紹了javascript閉包的高級(jí)使用方法實(shí)例,有需要的朋友可以參考一下2013-07-07JavaScript遞歸操作樹形結(jié)構(gòu)代碼示例
前端樹形結(jié)構(gòu)一般用于網(wǎng)頁的地理位置輸入框,地理位置級(jí)聯(lián)選擇,人員的部門選擇等,這篇文章主要給大家介紹了關(guān)于JavaScript遞歸操作樹形結(jié)構(gòu)的相關(guān)資料,需要的朋友可以參考下2024-01-01關(guān)于JSONP跨域請(qǐng)求原理的深入解析
JSONP(JSON?with?Padding)是JSON的一種“使用模式”,可用于解決主流瀏覽器的跨域數(shù)據(jù)訪問的問題,這篇文章主要給大家介紹了關(guān)于JSONP跨域請(qǐng)求原理的相關(guān)資料,需要的朋友可以參考下2022-01-01