vue --- axios发post请求后台接收不到参数的三种解决方案

最近用vue  做项目使用axios 发送post 请求时遇到了前端传数据后端接收不到的情况:

后来仔细对比发现axios传值是这样的:

而 ajax 传值是这样的:

一个 Request Payload ,  一个Form data.

将Request payload 转为 from data 格式就可以了。有四种方式:

一:使用qs(推荐)

首先在你的项目里安装qs 模块。

npm install qs --save-dev

然后在需要使用的页面引入一下:

import qs from 'qs'

引入好了之后,把上面的postData用qs转一下再发送给后台就可以了:

let postData = qs.stringify({
        certificationAccount: that.certificationAccount,
        balance: that.balance
})

这样发送给后台时就是Format Data格式了。

二:使用URLSearchParams ;

let postData= new URLSearchParams()
postData.append('certificationAccount',  that.certificationAccount)
postData.append('balance',  that.balance)

这样也可以,个人觉得写起来麻烦。

三、直接使用字符串

let postData ='certificationAccount =' + that.certificationAccount + '&balance=' + that.balance

 es6写法:

let postData = `
          certificationAccount = ${that.certificationAccount}&balance=${that.balance}
`

 四:JSON.stringify()

猜你喜欢

转载自www.cnblogs.com/yuerdong/p/10277177.html