Axios学习
then分支
走的是状态码为 [200,300) 进入的分支
error分支
走的是状态码[300,511]进入的分支 封装的错误信息在error.response.data内
前端
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- import CSS -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<style type="text/css">
.div_space{
padding-top:20px;
margin-bottom:20px;
}
</style>
</head>
<body>
<div id="app">
<div class="div_space" style="width:20%;margin:0 auto;margin-top:100px;max-length:200px;">
<el-col ><el-input clearable v-model="account.username" placeholder="请输入账号"></el-input></el-col>
</div>
<div class="div_space" style="clear:both;width:20%;margin:20px auto;max-length:200px;">
<el-col ><el-input clearable placeholder="请输入密码" v-model="account.password" show-password></el-input></el-col>
</div>
<div class="div_space" style="clear:both;text-align:center">
<el-button type="primary" @click="sign()">登录</el-button>
<el-button type="warning" @click="verify()">验证</el-button>
</div>
</div>
</body>
<!-- import Vue before Element -->
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<!-- import JavaScript -->
<script crossorigin="anonymous" integrity="sha384-WbhdtWslh0AUD1Dhf8OExUvvjZ/VN6o2HHMsYlDXb6uf3IweMH13dGL4V/KgDc7y" src="https://lib.baomitu.com/element-ui/2.13.2/index.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/js-cookie/2.2.1/js.cookie.js"></script>
<script>
new Vue({
el: '# app',
data: function() {
return {
url:"http://127.0.0.1:8601",
auth:{
accessToken:"",
refreshToken:""
},
account:{
username:"",
password:""
}
}
},methods:{
sign(){
axios({
url:this.url+"/login",
method: 'POST',
data:{username:this.account.username,password:this.account.password}
})
.then(response =>{
console.log(response)
if(response.data.code==0)
this.$message.success("登录成功!,分发token")
this.auth.accessToken = response.data.data.accessToken
this.auth.refreshToken = response.data.data.refreshToken
this.setCookie("accessToken",this.auth.accessToken)
this.setCookie("refreshToken",this.auth.refreshToken)
console.log(this.getCookie("accessToken"),"------------------")
console.log(response.data)
})
.catch((error) =>{
console.log(error.response)
this.$message.error(error.response.data.msg+":"+error.response.data.data)
})
},
verify(){
axios({
url:this.url+"/status",
headers: {
'token': this.auth.accessToken
}
}).then(response =>{
console.log(response.data)
if(response.data.code==0)
this.$message.success("权限验证通过")
else{
this.refreshAuth(this.auth.accessToken)
}
})
.catch((error) =>{
this.$message.error(error)
})
},refreshAuth(accessToken){
axios({
url:this.url+"/auth",
headers: {
'accessToken': accessToken,
'refreshToken': this.auth.refreshToken
}
}).then(response =>{
console.log(response.data)
if(response.data.code==0){
this.$message.success("refreshToken success!")
this.auth.accessToken = response.data.data.accessToken
}
else{
this.$message.error(response.data.msg)
}
})
.catch((error) =>{
this.$message.error(error)
})
},setCookie(key,value){
return Cookies.set(key,value);
},getCookie(key){
return Cookies.get(key);
}
//***************
}
})
</script>
</html>
后端
正常分支
@PostMapping("/login")
public ResponseEntity<R<TokenDTO>> login(@Valid @RequestBody AutoDTO autoDTO, HttpServletRequest request) {
//登录成功
String accessToken,refreshToken;
TokenDTO tokenDTO=null;
try {
//accessToken为2分钟
accessToken = JwtUtil.sign(autoDTO.getUsername() + ""+autoDTO.getPassword(),1000*5);
//refreshToken过期时间为七天
refreshToken = JwtUtil.sign(autoDTO.getUsername() + ""+autoDTO.getPassword(),1000*60*60*24*7);
//builder模式重构
tokenDTO=TokenDTO.builder().accessToken(accessToken).refreshToken(refreshToken).build();
} catch (Exception e) {
log.error("api in /login has exception about"+e);
}
//异步存储登陆日志
log.info("登录日志 \t\t-->"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"\t\t-->ip:"+request.getRemoteHost()+"\t\t-->"+autoDTO.getUsername()+"已登入");
return ResponseEntity.status(HttpStatus.OK).body(R.ok(tokenDTO));
}
异常分支
@ControllerAdvice
public class ValidExceptionHandler {
private final static String EXCEPTION_MSG_KEY = "Exception message : ";
@ResponseBody
@ExceptionHandler({org.springframework.validation.BindException.class})
public ResponseEntity<R<String>> handleValidException(BindException e) {
//日志记录错误信息
log.error(Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage());
//将错误信息返回给前台
// return R.restResult(Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage(), ApiErrorCode.FAILED);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(R.restResult(Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage(), ApiErrorCode.FAILED));
}
// MethodArgumentNotValidException.class
@ResponseBody
@ExceptionHandler({MethodArgumentNotValidException.class})
public ResponseEntity<R<String>> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
//日志记录错误信息
log.error(Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage());
//将错误信息返回给前台
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(R.restResult(Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage(), ApiErrorCode.FAILED));
}
}