今天前端使用Vue传入参数,后端接收时发现在参数末尾多了一个等于号=
前端:
1 <template> 2 <div> 3 <el-input v-model="phoneNum" placeholder="请输入手机号"/> 4 <el-button @click="sendVerifyCode(phoneNum)">发送验证码</el-button> 5 <el-input v-model="verifyCode" placeholder="请输入验证码"/> 6 <el-button @click="checkVerifyCode(phoneNum, verifyCode)">提交</el-button> 7 </div> 8 </template> 9 10 <script> 11 export default { 12 name: "Login", 13 data(){ 14 return{ 15 phoneNum: '', 16 verifyCode: '' 17 } 18 }, 19 methods:{ 20 sendVerifyCode(phoneNum){ 21 console.log(phoneNum); 22 axios.post('http://localhost:8181/verifyCode/sendVerifyCode', phoneNum) 23 .then(response => { 24 console.log(response) 25 }) 26 }, 27 checkVerifyCode(phoneNum, verifyCode){ 28 console.log(phoneNum, verifyCode) 29 } 30 } 31 } 32 </script> 33 34 <style scoped> 35 36 </style>
后端:
1 @PostMapping("sendVerifyCode") 2 public String sendVerifyCode(@RequestBody String phoneNum){ 3 logger.info(phoneNum); 4 Boolean flag = verifyCodeService.setVerifyCode(phoneNum); 5 if(flag){ 6 return "success"; 7 } 8 return "failed"; 9 }
在后端接收参数时,发现参数值的末尾会自动添加一个等于号=
仔细分析就能发现,原来是没有把参数包装成FormData传入,导致传入的参数不正确:
所以显然,我们需要再进行封装,把参数封装进FormData中
const formData = new FormData(); formData.append("phoneNum", phoneNum);
此时:
后端即可正确接收。