Vue 设置axios请求格式为form-data的操作步骤

Cover

Vue 设置axios请求格式为form-data的操作步骤

在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的操作步骤就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容