axios模拟表单提交

axios默认是application/json方式提交,controller接收的时候必须以@RequestBody的方式接收,有时候不太方便。如果axios以application/x-www-form-urlencoded方式提交数据,controller接收的时候只要保证名字应对类型正确即可。

前端代码:

  
    
      
        
      
      
        
      
    
    
    
  

这是利用Element-Plus模态框提供的三个SLOT(footer,header和default)嵌套了一个Element-Plus的表单。点击登录按钮时,将双向绑定的formData提交到controller。

点击登录按钮时出发的formConfirm方法:

const formConfirm=function (){
  this.dialogVisible=false;
  axios.post(url.login,formData,{
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}
              }
      )
      .then(resp=>{
        const data = resp.data;
        this.formData.username="";
        this.formData.password="";
        console.log(data);
      })
      .catch(err=>{
            console.log("login error: ",err);
          }
      );
}

核心就是使用了三参数的post函数:

post(url,data,config)

config里面设定发起post请求时的额外设置,header是设置(config)的一部分,而header中需要显式的设置content-type为application/x-www-form-urlencoded,这样对于服务器来说这就是一个表单提交数据的请求。

后端controller:

 @PostMapping("/login")
    public Map login(String username, String password){
        log.info("username--->{}",username);
        log.info("password--->{}",password);
        Map resp =   new HashMap<>();
        resp.put("message","wrong name or password");
        resp.put("token",null);
        if("abc".equals(username) && "123456".equals(password)){
            String token = UUID.randomUUID().toString();
            stringRedisTemplate.opsForValue().set("token",token,3600, TimeUnit.SECONDS);
            resp.put("message","success");
            resp.put("token",token);
            return resp;
        }
        return resp;
    }

如果是表单提交的数据,那么handler接收的方式不用添加任何额外的注解,利用名称对应,类型正确的方式就可以接收表单数据了。

你可能感兴趣的:(axios,spring,boot)