- 安装 axios、qs
npm install qs axios --save
src目录下新建http.js
import axios from "axios";
import store from "@/store";
import { MessageBox, Message } from "element-ui";
import qs from "qs";
import { isPlainObject } from '@/utils'
import { getToken } from "@/utils/auth";
const service = axios.create({
baseURL: '',
timeout: 99999
})
service.interceptors.request.use((config) => {
if (config.headerType === 1) {
config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
config.data = qs.stringify(config.data)
} else {
config.headers['Content-Type'] = 'application/json;charset=UTF-8'
if (isPlainObject(config.data)) qs.stringify(config.data)
}
const apiList = [
'/login',
'/captchaImage',
]
if (
!apiList.includes(config.url.replace(process.env.VUE_APP_BASE_API, '')) &&
getToken()
) {
config.headers['Authorization'] = getToken()
}
return config
},
(error) => {
console.log(error);
return Promise.reject(error);
}
);
service.interceptors.response.use(
(response) => {
const res = response.data;
if (res.code !== 200) {
Message({
message: res.msg || "Error",
type: "error",
duration: 3 * 1000,
});
if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
MessageBox.confirm(
"登录状态已过期,您可以继续留在该页面,或者重新登录",
"系统提示",
{
confirmButtonText: "重新登录",
cancelButtonText: "取消",
type: "warning",
}
).then(() => {
store.dispatch("user/resetToken").then(() => {
location.reload();
});
});
}
return Promise.reject(new Error(res.msg || "Error"));
} else {
return res;
}
},
(error) => {
console.log("err" + error);
Message({
message: error.msg,
type: "error",
duration: 3 * 1000,
});
return Promise.reject(error);
}
);
export default service;
import qs from 'qs';
const isPlainObject = function isPlainObject(obj) {
let proto, Ctor;
if (!obj || Object.prototype.toString.call(obj) !== "[object Object]") return false;
proto = Object.getPrototypeOf(obj);
if (!proto) return true;
Ctor = proto.hasOwnProperty('constructor') && proto.constructor;
return typeof Ctor === "function" && Ctor === Object;
};
let baseURL = 'http://127.0.0.1:9999',
inital = {
method: 'GET',
params: null,
body: null,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
export default function request(url, config) {
if (typeof url !== "string") throw new TypeError('url must be required!');
if (!isPlainObject(config)) config = {};
if (config.headers) {
if (!isPlainObject(config.headers)) config.headers = {};
config.headers = Object.assign({}, inital.headers, config.headers);
}
let {
method,
params,
body,
headers
} = Object.assign({}, inital, config);
if (!/^http(s?):\/\//i.test(url)) url = baseURL + url;
if (params != null) {
if (isPlainObject(params)) params = qs.stringify(params);
url += `${url.includes('?')?'&':'?'}${params}`;
}
let isPost = /^(POST|PUT|PATCH)$/i.test(method);
if (isPost && body != null && isPlainObject(body)) {
body = qs.stringify(body);
}
config = {
method: method.toUpperCase(),
headers
};
if (isPost) config.body = body;
return fetch(url, config).then(response => {
let {
status,
statusText
} = response;
if (status >= 200 && status < 300) {
return response.json();
}
return Promise.reject({
code: 'STATUS ERROR',
status,
statusText
});
}).catch(reason => {
if (reason && reason.code === "STATUS ERROR") {
}
if (!navigator.onLine) {
}
return Promise.reject(reason);
});
};
src目录下新建index.js
可以不同页面的接口写在不同的js文件中,按照模块划分,导入到index.js中
import axios from './http';
import request from './http2';
function getList(options={}){
options = Object.assign({
src: 'web',
alist: '',
pageNum: 1
})
}
const queryUserInfo = userId => {
return request('/user/info', {
params: {
userId
}
});
};
const setUserLogin = (account, password) => {
return request('/user/login', {
method: 'POST',
body: {
account,
password
}
});
};
export default {
queryUserInfo,
setUserLogin
};
main.js引用
import Vue from 'vue';
import App from './App.vue';
import api from './api/index';
Vue.config.productionTip = false;
Vue.prototype.$api = api;
new Vue({
render: h => h(App)
}).$mount('#app');
- 页面引用
methods: {
async getData(){
this.loading = true
let { d, s } = await this.$api.homeList.getList({
pageNum: 1,
alias: ""
})
this.loading = false
if(s == 1){
if(d && d.length>0){
d = d.map(item => Object.freeze(item))
this.source.push(...d)
return
}
this.fiinished = true
}
},
async loadMore() {
this.pageNum += 1
await this.querData()
}
}