Skip to content

Commit

Permalink
引入并封装axios请求
Browse files Browse the repository at this point in the history
  • Loading branch information
pjqdyd committed Aug 11, 2019
1 parent bde4329 commit d96f057
Show file tree
Hide file tree
Showing 6 changed files with 189 additions and 2 deletions.
37 changes: 37 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"lint": "vue-cli-service lint"
},
"dependencies": {
"axios": "^0.19.0",
"core-js": "^2.6.5",
"element-ui": "^2.9.1",
"lodash": "^4.17.14",
Expand Down
7 changes: 7 additions & 0 deletions src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,16 @@ import i18n from './i18n/i18n'
import 'element-ui/lib/theme-chalk/index.css'
import './assets/iconfont/iconfont.css'

import http from './utils/http'; //引入请求工具

Vue.config.productionTip = false
Vue.use(ElementUI)

//挂载全局请求
Vue.prototype.$globalRequest = http.globalRequest;
Vue.prototype.$userRequest = http.userRequest;


new Vue({
router,
store,
Expand Down
113 changes: 113 additions & 0 deletions src/utils/http.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import axios from 'axios'
import { createError } from './util'
import { Message } from 'element-ui';

//const ip = 'http://localhost:8080'; //baseUrl
const ip = 'https://www.easy-mock.com/mock/5c8dd97d6fe7c7611499c703'

// 统一配置请求
const HTTP_REQUEST = axios.create({
baseURL: ip,
responseType: 'json',
validateStatus(status) {
// 200 外的状态码都认定为失败
return status === 200
}
})

// 统一拦截请求
HTTP_REQUEST.interceptors.request.use((config) => {
// 有 token就带上
// if (this.$store.state.token) {
// config.headers.Authentication = store.state.token
// }
return config
}, (error) => {
return Promise.reject(error)
});

// 统一拦截响应
HTTP_REQUEST.interceptors.response.use((config) => {
return config
}, (error) => {
//TODO
return Promise.reject(error)
});

//定义异步请求方法,(如果返回有异常就提示信息,并抛出异常)
const doRequest = async (request) => {
try {
const resp = await request;
const data = resp.data;
if (!data) {
if (resp.status === 201 || resp.status === 203 || resp.status === 204) {
return ''
}
} else {
return data
}
} catch (err) {
const errResp = err.response;
console.log('---------------', err);
if (errResp.status === 404) {
Message.error('错误, 未找到数据');
throw createError(errResp.status, "错误, 未找到数据");
} else if (errResp.status === 401) {
Message.error('错误, 您无权访问');
throw createError(errResp.status, '错误, 您无权访问');
} else {
Message.error(errResp.message);
throw err;
}
}
}


/**
* 功能描述:全局 API请求集合
*/
const globalRequest = {

//测试1
test(name, age) {
return doRequest(HTTP_REQUEST.get(`/test?name=${name}&age=${age}`))
},

//测试2
test2(name, params) {
return doRequest(HTTP_REQUEST.get(`/test2?name=${name}`, params, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}))
},

//测试3
test3(name, bodyData) {
return doRequest(HTTP_REQUEST.post(`/test3?name=${name}`, bodyData, {headers: {'Content-Type': 'application/json'}}))
},

//测试4
test4(id) {
return doRequest(HTTP_REQUEST.get(`/test/userinfo?id=${id}`, {headers: {'Content-Type': 'application/json'}}))
}

}

/**
* 功能描述:用户 API请求集合
*/
const userRequest = {

//登录
login(username, password) {
return doRequest(HTTP_REQUEST.post(`/login?username=${username}&password=${password}`))
}

}


//导出所有请求
export default{

globalRequest,

userRequest

}
13 changes: 13 additions & 0 deletions src/utils/util.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export const createError = (code, msg) => {
const err = new Error(msg)
err.code = code
err.msg = msg
return err
}


// 日期格式转换
export const formatDateTime = (date) => {
let dateee = new Date(date).toJSON();
return new Date(+new Date(dateee) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
}
20 changes: 18 additions & 2 deletions src/views/page-1/PageOne.vue
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
<template>
<div>
<!-- <div id="page-one" class="page-one" :style=" 'height:'+curHeight+'px' ">1</div> -->
<div id="page-one" class="page-one">1</div>
<div id="page-one" class="page-one">1
<el-button @click="handRequestTest">测试</el-button>
</div>
</div>
</template>

Expand All @@ -18,7 +20,21 @@ export default {
//var h = document.documentElement.clientHeight || document.body.clientHeight;
//this.curHeight = h; //获取窗口height
},
methods: {}
methods: {
//测试
async handRequestTest(){
console.log("test");
try {
var result= await this.$globalRequest.test4(1001); //测试请求
console.log(result);
this.$message.success('测试成功');
} catch (err) {
this.$message.info(err.msg);
}
}
}
};
</script>

Expand Down

0 comments on commit d96f057

Please sign in to comment.