- 安装 axios、qs
npm install qs axios --save
src
目录下新建http.js
- axios
import axios from 'axios';
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;
};
// 会基于NODE环境变量,配置不同的BASEURL地址
axios.defaults.baseURL = 'http://127.0.0.1:9999';
axios.defaults.timeout = 10000;
axios.defaults.withCredentials = true;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.transformRequest = function (data) {
if (!isPlainObject(data)) return data;
return qs.stringify(data);
};
axios.interceptors.request.use(config => {
let token = localStorage.getItem('token');
if (token) config.headers['Authorization'] = token;
return config;
});
axios.interceptors.response.use(function onfulfilled(response) {
return response.data;
}, function onrejected(reason) {
// @1 服务器返回信息,状态码不是以2开始
if (reason.response) {
switch (reason.response.status) {
case 400:
// ...
break;
}
}
// @2 服务器没有返回的信息「请求超时或者中断」
if (reason.code === "ECONNABORTED") {
// ...
}
// @3 服务器没有返回的信息「断网了」
if (!navigator.onLine) {
// ...
}
return Promise.reject(reason);
});
export default axios;
- Fetch
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);
// 处理URL
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 => {
// 只要服务器有返回值,则都认为promise是成功的,不论状态码是啥
let {
status,
statusText
} = response;
if (status >= 200 && status < 300) {
// response.json():把服务器获取的结果变为json格式对象,返回的一个promise实例
return response.json();
}
return Promise.reject({
code: 'STATUS ERROR',
status,
statusText
});
}).catch(reason => {
// @1 状态码错误
if (reason && reason.code === "STATUS ERROR") {
// ...
}
// @2 断网
if (!navigator.onLine) {
// ...
}
return Promise.reject(reason);
});
};
src
目录下新建index.js
import axios from './http';
import request from './http2';
const queryUserInfo = userId => {
/* return axios.get('/user/info', {
params: {
userId
}
}); */
return request('/user/info', {
params: {
userId
}
});
};
const setUserLogin = (account, password) => {
/* return axios.post('/user/login', {
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');
/*
$.ajax 导入JQ 基于回到函数管理的
$.ajax({
url:'/api/list',
success(result){
}
});
axios 下载安装这个模块 基于Promise封装的ajax库
axios.get('/api/list').then(result=>{
return axios.get('/api/info');
}).then(result=>{
});
------上述两种办法都是基于 XMLHttpRequest 方案完成的
fetch 直接用(ES6),本身就是基于Promise管理的,和XMLHttpRequest没有任何关系,是浏览器新提供的一种前后端数据通信方案
https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch
*/