- 在项目开发过程中,为了方便统一操作,通常会把API封装到一个文件里,在页面直接使用就可以了,避免后端修改接口的时候在每一个发请求的页面修改。
- 鉴于这个项目对API的封装不同于以往的做法,我决定记录自己封装的每一个API。
- 获取后端图形验证API封装:
const HOST = "http://192.168.0.135";
const CAPRCHA = HOST + "/captcha.jpg";
export function getCaptcha(successFn) {
axios.get(CAPRCHA)
.then(function(res) {
if (res.status == 200) {
var imgUrl = res.config.url
successFn(imgUrl);
}
})
.catch(function(error) {
console.log(error);
});
}
export default {
getCaptcha: getCaptcha
}
import { getCaptcha, getUserInfo} from "@/api/index.js";
mounted() {
const _this = this;
getCaptcha(_this.showImg);
},
export function getUserInfo(data,successFn) {
axios.post(LOGIN + "?t=" + new Date().getTime(), data)
.then(function(response) {
console.log(response);
if (response.data.code == 500) {
getCaptcha()
}
if(response.data.code==200){
successFn()
}
})
.catch(function(error) {
console.log(error);
});
}
const LOGIN = HOST + "/login";
login() {
var data={loginName:this.form.username, loginPassword:this.form.password,captcha:this.form.code
}
getUserInfo(data,this.toIndex)
,toIndex(){
this.$router.push("/index");
}