Vue使用axios,设置axios请求格式为form-data
生活随笔
收集整理的這篇文章主要介紹了
Vue使用axios,设置axios请求格式为form-data
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
Vue使用axios,設(shè)置axios請求格式為form-data
這個老生常談了,還是先記錄一遍,方面后面自己查。
!!! 設(shè)置form-data請求格式直接翻到后面看。
1. 安裝axios
在項目下執(zhí)行npm install axios。
之后在main.js中,添加:
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) //錯誤信息 })與上面相同,就是參數(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) //錯誤信息 })axios也可以用jQ的寫法,不過回調(diào)函數(shù)還是Promise的寫法,如:
this.$axios({method: 'post',url: '...',data: {firstName: 'Fred',lastName: 'Flintstone'} }).then((res) => {console.log(res) })設(shè)置form-data請求格式
我用默認的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總結(jié)
以上是生活随笔為你收集整理的Vue使用axios,设置axios请求格式为form-data的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 抖音app(抖音下载正版)
- 下一篇: axios请求拦截 做Loading加