Cover
在Vue中使用axios
这个老生常谈了,还是先记录一遍,方面后面自己查。
!!! 设置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) //错误信息 })
2. 发送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) //错误信息 })
3. 经典写法
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请求格式为form-data的操作步骤就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com
暂无评论...
更新日志
2024年09月23日
2024年09月23日
- 金池VS刘罡2009《双声情》[WAV+CUE]
- 冯奥迪《卄》[320K/MP3][67.08MB]
- 冯奥迪《卄》[FLAC/分轨][172.46MB]
- Merryland《Merryland》[320K/MP3][69.48MB]
- 苏芮.1991-停在我心里的温柔【福茂】【WAV+CUE】
- 苏慧伦.2020-面面Every.Side.of.Me【相信音乐】【WAV+CUE】
- 群星.1991-不一样的感觉REMIX【宝丽金】【WAV+CUE】
- 银霞.1983-《你那好冷的小手》珍藏纪念版[WAV分轨]
- 银霞.2002-《国语巨星专辑VOL.3》2CD台湾版[WAV+CUE]
- 金池刘罡《昨日情歌HQ》头版限量编号[低速原抓WAV+CUE]
- 段奥娟.2024-23·岁碎念【白米范】【FLAC分轨】
- 顺子.2001-昨日·唯一·更多·顺子自选辑【魔岩】【WAV+CUE】
- 无印良品.1999-私藏三首·原创相对论(EP)【滚石】【WAV+CUE】
- Merryland《Merryland》[FLAC/分轨][170.22MB]
- 庄锭欣 ELKIE《没有你的未来》[320K/MP3][15.78MB]