后端无法接收前端传递的参数

时间:2025-03-20 09:26:38

错误描述

前端发送代码如下

login() {
      let {userCode, userPwd} = this.ruleForm;
      // this.$('/UserInfoService/login',
      //     this.$({
      //       account: userCode,
      //       password: userPwd
      //     })).then(res => {
      //   (res);
      // })
      this.$axios({
        method: 'post',
        url: '/UserInfoService/login',
        data: {
          account: userCode,
          password: userPwd
        }
      }).then(res => {
        console.log(res);
      })
    },

请求体内容如下

{account: "111", password: "222"}
account: "111"
password: "222"

后端无论将属性拆开或者用userInfo实体去接收都得到的是null

错误原因

​ 原因是axios默认的发送数据格式是json格式,不是form-data,导致传递到后端的数据是json格式,后端无法直接接收,在返回结果时,就会将前端发送的数据传递给前端.

解决方案

有两种解决方案,如下

  • 第一种为将前端传送数据的格式改为form-data

    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    

    但是这种方法不推荐,因为前后端通讯时使用的是json格式

  • 第二种是用实体类去接收前端传递的参数,并将参数用@RequestBody去修饰