Vue: 将axios封装为Javascript对象
本篇博客的主要目标: 在Vue-CLI项目中封装axios为Javascript对象
1. main.js
引用axios、vue-axios
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import axios from 'axios'
import VueAxios from 'vue-axios'
import './registerServiceWorker'
Vue.config.productionTip = false;
Vue.use(VueAxios, axios);
new Vue({
router,
store,
render: h => h(App),
}).$mount('#app')
2. Http.js
使用 Promise
封装HTTP:
import axios from 'axios'
const http = options => {
return new Promise((resolve, reject) => {
const defaultOptions = {};
const newOptions = {
...defaultOptions,
...options
};
// headers默认传递json格式数据,这里也可以设置token,每次调用都会携带
newOptions.headers = {
'content-Type': 'application/json;charset=UTF-8',
...newOptions.headers
};
// 这里可以在调用的时候看到你的method、url、data、headers等参数
// console.log(newOptions);
axios({
headers: newOptions.headers,
method: newOptions.method,
url: newOptions.url,
data: newOptions.data,
responseType: newOptions.responseType
}).then(res => {
// 根据返回的状态码判断,注意res返回的并不一定都是status,比如小程序就是statusCode
if (res.status == 200) {
// console.log(newOptions);
// 这里我们只需要获取返回的data中的数据即可
resolve(res.data);
} else {
reject(res);
}
}).catch(err => {
reject(err);
})
})
};
export default http
3. .vue 文件使用
目录层次结构如下:
<script>
import http from '@/api/http'
export default {
name: 'Login',
data () {
return {
username: null,
password: null
}
},
methods: {
login() {
if (this.username == null || this.username == "" || this.password == "" || this.password == null) {
this.$message.warning("userName and password can't be empty!");
} else { // 输入合法
var _this = this;
http({
// 假设后台需要的是表单数据这里你就可以更改
headers: {
"Content-Type": "application/json;charset=UTF-8"
},
method: 'post',
// 你的后端接口地址
url: 'http://localhost:8080/xxxx',
data: {
username: _this.username,
password: _this.password
},
responseType: 'json'
// 直接使用function, 而不使用箭头函数时, 不可以直接使用this
// function有独立的作用域
}).then(function (res) {
var code = res.code;
var info = res.info;
if (res.code == 200) {
console.log(info);
_this.$router.push("/home");
} else {
console.log(info);
}
// 使用箭头函数时, 则可以直接使用this
// 箭头函数没有独立的作用域
}).catch((err) => {
console.log(err);
});
}
}
}
}
</script>
由于这里采用 JSON
类型作为 数据交换格式,故 responseType: 'json’
后端 JSON 数据格式如下,这里的 JSON 格式采用 Alibaba 的 fastjson,这里也非常推荐大家使用 fastjson
,因为其非常简单,并且好用!:
import com.alibaba.fastjson.JSONObject;
import sun.compiler.constants.Constants;
/**
* 封装 HTTP 请求
* author: Sun Rui
* 2020.07.21
*/
public class JSONUtil {
public static JSONObject successJSON() {
JSONObject resultJson = new JSONObject();
resultJson.put("info", "QUERY_SUCCESS");
resultJson.put("msg", "QUERY_SUCCESS");
resultJson.put("code", 200);
return resultJson;
}
public static JSONObject successJSON(Object info) {
JSONObject resultJson = new JSONObject();
resultJson.put("info", info);
resultJson.put("msg", "QUERY_SUCCESS");
resultJson.put("code", 200);
return resultJson;
}
public static JSONObject errorJSON(Object info) {
JSONObject resultJson = new JSONObject();
resultJson.put("info", info);
resultJson.put("msg", "QUERY_FAILED");
resultJson.put("code", "400");
return resultJson;
}
}