一畦浓、在src下新建http.js和api.js
接口請(qǐng)求封裝:http.js
import axios from 'axios';
const withAxios = apiConfig => {
// 環(huán)境的切換
if (process.env.NODE_ENV == 'development') {
axios.defaults.baseURL = 'http://192.168.1.231:9000/admin';}
else if (process.env.NODE_ENV == 'debug') {
axios.defaults.baseURL = 'http://192.168.1.231:9000';
}
else if (process.env.NODE_ENV == 'production') {
axios.defaults.baseURL = 'http://192.168.1.231:9000';
}
const token = window.localStorage.getItem('token');
const serviceMap = {};
apiConfig.map(({ name, url, method }) => {
serviceMap[name] = async function (data = {}) {
let key = "";
if (method === "post" || method === "put") {
key = "data";
}
return axios({
method,
url: url,
[key]: data,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
dataType: 'json'
});
};
});
return serviceMap;
};
export default withAxios;
接口api統(tǒng)一封裝: api.js
import withAxios from "./http.js";
const apiConfig = [
{
name: "login",
url: "/auth",
method: "post"
},
{
name: "userList",
url: "/user/listPage?page=1&size=10",
method: "get"
},
];
export default withAxios(apiConfig);
引入和定義方式:main.js中
import http from 'http.js'
import ports from 'ports'
Vue.prototype.http = http
Vue.prototype.ports = ports
使用 方式:組件內(nèi)
this.http.post(this.ports.manage.login, {
userAccount: 'test',
userPassword: '111111',
cert: '1111111111'
}, res => {
if (res.success) {
// 返回正確的處理
} else {
// 返回錯(cuò)誤的處理
}
})
接口請(qǐng)求只添加了一個(gè)token项阴,具體的還需要自己設(shè)置一下。