Vue axios 发 post 请求后台接收不到参数的两种种解决方案:
最近用vue做项目使用axios发送post请求时遇到了前端传数据后端接收不到的情况:代码:后来仔细对比ajax发现axios传值是这样的:而ajax传值是这样的:一个Request Payload,一个Form Data。将Request Payload 转为Form Data格式就可以了,有三种方式:一、使用qs(推荐)首先在你的项目里安装qs模块:npm install...
·
最近用vue做项目使用axios发送post请求时遇到了前端传数据后端接收不到的情况:
代码:
后来仔细对比ajax发现axios传值是这样的:
而ajax传值是这样的:
一个 Request Payload,一个 Form Data。
将 Request Payload 转为 Form Data 格式就可以了,有三种方式:
一、使用 qs (application/x-www-form-urlencoded)
首先在你的项目里安装qs模块:
npm install qs --save-dev
然后在需要使用的页面引入一下:
import qs from 'qs'
引入好了之后,把上面的 postData 用 qs 转一下再发送给后台就可以了:
// 数据接口
const getData = Axios.create({
baseURL: 'url',
withCredentials: true,// 跨域
headers: {
// 数据类型 axios 默认就是下面的,也可以不设置
'Content-Type': 'application/x-www-form-urlencoded',
},
})
Vue.prototype.$http = getData
let form = qs.stringify({
phone: this.loginPhone,
password: this.loginPassword
});
this.$http.post('url', form)
.then(res => {
console.log(res.data);
})
这样发送给后台时就是Format Data格式了。
二、使用 FormData (multipart/form-data)
// 基于vue的形式
var form = new FormData();
form.append('name', this.name);
form.append('phone', this.phone);
form.append('sex', this.sex);
form.append('photo', this.img);
form.append('user_address', this.address);
let config = {
headers: {'Content-Type': 'multipart/form-data'}
}; //添加请求头
if (this.$refs.person.validate()) {
this.$http.post('url', form, config)
.then(response => {
console.log(response.data);
})
}
更多推荐
已为社区贡献19条内容
所有评论(0)