這篇文章將為大家詳細(xì)講解有關(guān)Vue如何設(shè)置axios請求格式為form-data,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
Cover
在Vue中使用axios
!!! 設(shè)置form-data請求格式直接翻到后面看。
1. 安裝axios
在項目下執(zhí)行npm install axios。
之后在main.js中,添加:
import axios from 'axios' //引入 //Vue.use(axios) axios不能用use 只能修改原型鏈 Vue.prototype.$axios = axios
2. 發(fā)送GET請求
axios封裝了get方法,傳入請求地址和請求參數(shù),就可以了,同樣支持Promise。
//不帶參數(shù)的get請求 let url = "..." this.$axios.get(url) .then((res) => { console.log(res) //返回的數(shù)據(jù) }) .catch((err) => { console.log(err) //錯誤信息 })
不過它的參數(shù)需要寫在params屬性下,也就是:
//帶參數(shù)的get請求 let url = "...getById" this.$axios.get(url, { params: { id: 1 } }) .then((res) => { console.log(res) //返回的數(shù)據(jù) }) .catch((err) => { console.log(err) //錯誤信息 })
2. 發(fā)送post請求
與上面相同,就是參數(shù)不需要寫在params屬性下了,即:
//帶參數(shù)的post請求 let url = "...getById" let data = { id: 1 } this.$axios.post(url, data) .then((res) => { console.log(res) //返回的數(shù)據(jù) }) .catch((err) => { console.log(err) //錯誤信息 })
3. 經(jīng)典寫法
axios也可以用jQ的寫法,不過回調(diào)函數(shù)還是Promise的寫法,如:
this.$axios({ method: 'post', url: '...', data: { firstName: 'Fred', lastName: 'Flintstone' } }).then((res) => { console.log(res) })
設(shè)置form-data請求格式
我用默認(rèn)的post方法發(fā)送數(shù)據(jù)的時候發(fā)現(xiàn)后端獲取不到數(shù)據(jù),然而在network中看到參數(shù)是的確傳出去的了。而且用postman測試的時候也是可以的,比較了下兩個的不同發(fā)現(xiàn)是postman使用的是form-data格式,于是用form-data格式再次請求,發(fā)現(xiàn)OJBK
在查找設(shè)置請求格式的時候花了點時間,網(wǎng)上的方案有好幾個,這個我親測成功,發(fā)上來。
import axios from "axios" //引入 //設(shè)置axios為form-data axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; axios.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded'; axios.defaults.transformRequest = [function (data) { let ret = '' for (let it in data) { ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&' } return ret }] //然后再修改原型鏈 Vue.prototype.$axios = axios
關(guān)于“Vue如何設(shè)置axios請求格式為form-data”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
文章名稱:Vue如何設(shè)置axios請求格式為form-data-創(chuàng)新互聯(lián)
當(dāng)前路徑:http://vcdvsql.cn/article40/jidho.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站導(dǎo)航、定制開發(fā)、定制網(wǎng)站、網(wǎng)站策劃、網(wǎng)站制作、App設(shè)計
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容