uni-app后端收到前端数据为null

652 阅读1分钟

问题与解决措施:

实现注册功能,插入一条新数据,包括用户的用户名、密码和手机号。使用uni.request请求传数据到后端接口。接口名称为http://localhost:8080/register,是POST请求。但是一开始后端收到的数据为null,查看前端数据是没有问题的,数据类型都是String类型。经过一番查阅之后发现需要加上请求头才能使后端正确接收到数据。

前端:

uni.request({
    url: 'http://localhost:8080/register',
    method: 'POST',
    data: {
        name: this.username,
        password: this.password,
        phone: this.phone
    },
    header: {
        'content-type': 'application/x-www-form-urlencoded'
    },
    success: (res) => {
        uni.showToast({
            title: '注册成功',
            icon: 'success'
        })
        uni.navigateBack()
    },
    fail: () => {
        uni.showToast({
            title: '注册失败',
            icon: 'error'
        })
    }
})

重要:

header: {
    'content-type': 'application/x-www-form-urlencoded'
}

后端:

@PostMapping("/register")
public void register(String name, String password, String phone) {
    userManageService.addNewUser(name, password, phone);
}

注意:

后端我并没有加@ResponseBody注解,但是为了不让程序解析为页面报错,必须将控制器的注解从@Controller改为@RestController,这一点值得注意。