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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

Vue使用axios,设置axios请求格式为form-data

發布時間:2023/12/31 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Vue使用axios,设置axios请求格式为form-data 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Vue使用axios,設置axios請求格式為form-data

這個老生常談了,還是先記錄一遍,方面后面自己查。

!!! 設置form-data請求格式直接翻到后面看。

1. 安裝axios

在項目下執行npm install axios。
之后在main.js中,添加:

import axios from 'axios' //引入//Vue.use(axios) axios不能用use 只能修改原型鏈 Vue.prototype.$axios = axios

2. 發送GET請求

axios封裝了get方法,傳入請求地址和請求參數,就可以了,同樣支持Promise

//不帶參數的get請求let url = "..." this.$axios.get(url) .then((res) => {console.log(res) //返回的數據 }) .catch((err) => {console.log(err) //錯誤信息 })

不過它的參數需要寫在params屬性下,也就是:

//帶參數的get請求let url = "...getById" this.$axios.get(url, {params: {id: 1} }) .then((res) => {console.log(res) //返回的數據 }) .catch((err) => {console.log(err) //錯誤信息 })
  • 發送post請求
  • 與上面相同,就是參數不需要寫在params屬性下了,即:

    //帶參數的post請求let url = "...getById" let data = {id: 1 }this.$axios.post(url, data) .then((res) => {console.log(res) //返回的數據 }) .catch((err) => {console.log(err) //錯誤信息 })
  • 經典寫法
  • axios也可以用jQ的寫法,不過回調函數還是Promise的寫法,如:

    this.$axios({method: 'post',url: '...',data: {firstName: 'Fred',lastName: 'Flintstone'} }).then((res) => {console.log(res) })

    設置form-data請求格式

    我用默認的post方法發送數據的時候發現后端獲取不到數據,然而在network中看到參數是的確傳出去的了。而且用postman測試的時候也是可以的,比較了下兩個的不同發現是postman使用的是form-data格式,于是用form-data格式再次請求,發現OJBK

    在查找設置請求格式的時候花了點時間,網上的方案有好幾個,這個我親測成功,發上來。

    import axios from "axios" //引入//設置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

    總結

    以上是生活随笔為你收集整理的Vue使用axios,设置axios请求格式为form-data的全部內容,希望文章能夠幫你解決所遇到的問題。

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