黑马程序员技术交流社区
标题:
【上海校区】封装uni-app的request请求
[打印本页]
作者:
梦缠绕的时候
时间:
2019-7-3 14:35
标题:
【上海校区】封装uni-app的request请求
http.js
//封装requset,uploadFile和downloadFile请求,新增get和post请求方法
let http = {
'setBaseUrl': (url) => {
if (url.charAt(url.length - 1) === "/") {
url = url.substr(0, url.length - 1)
}
http.baseUrl = url;
},
'header': {},
'beforeRequestFilter': (config) => { return config },
'beforeResponseFilter': (res) => { return res },
'afterResponseFilter': (successResult) => { },
'get': get,
'post': post,
'request': request,
'uploadFile': uploadFile,
'downloadFile': downloadFile
}
function init(con) {
//url
let url = http.baseUrl;
if (url && con.url && !con.url.match(/^(http|https):\/\/([\w.]+\/?)\S*$/)) {
if (con.url.charAt(0) !== "/") {
con.url = "/" + con.url;
}
con.url = url.concat(con.url);
}
//header
if (http.header != undefined && http.header != null) {
if (!con.header) {
con.header = http.header;
} else {
Object.keys(http.header).forEach(function (key) {
con.header[key] = http.header[key]
});
}
}
}
function request(con) {
init(con);
let config = {
url: con.url ? con.url : http.baseUrl,
data: con.data,
header: con.header,
method: con.method ? con.method : 'GET',
dataType: con.dataType ? con.dataType : 'json',
responseType: con.responseType ? con.responseType : 'text',
success: con.success ? (res) => {
http.afterResponseFilter(con.success(http.beforeResponseFilter(res)));
} : null,
fail: con.fail ? (res) => {
con.fail(res);
} : null,
complete: con.complete ? (res) => {
con.complete(res);
} : null
}
return uni.request(http.beforeRequestFilter(config));
}
function get(url, con, success) {
let conf = {};
if (con && typeof con == 'function') {
if (success && typeof success == 'object') {
conf = success;
}
conf.success = con
}else{
if (con && typeof con == 'object') {
conf = con;
}
conf.success = success;
}
if (url) {
conf.url = url
}
conf.method = "GET";
return request(conf);
}
function post(url, data, con, success) {
let conf = {};
if (con && typeof con == 'function') {
if (success && typeof success == 'object') {
conf = success
}
conf.success = con;
} else {
if (con && typeof con == 'object') {
conf = con;
}
conf.success = success;
}
if (url) {
conf.url = url
}
if (data) {
conf.data = data
}
conf.method = "POST";
return request(conf);
}
function uploadFile(con) {
init(con);
let config = {
url: con.url ? con.url : http.baseUrl,
files: con.files,
filesType: con.filesType,
filePath: con.filePath,
name: con.name,
header: con.header,
formData: con.formData,
success: con.success ? (res) => {
http.afterResponseFilter(con.success(http.beforeResponseFilter(res)));
} : null,
fail: con.fail ? (res) => {
con.fail(res);
} : null,
complete: con.complete ? (res) => {
con.complete(res);
} : null
}
return uni.uploadFile(http.beforeRequestFilter(config));
}
function downloadFile(con) {
init(con);
let config = {
url: con.url ? con.url : http.baseUrl,
header: con.header,
success: con.success ? (res) => {
http.afterResponseFilter(con.success(http.beforeResponseFilter(res)));
} : null,
fail: con.fail ? (res) => {
con.fail(res);
} : null,
complete: con.complete ? (res) => {
con.complete(res);
} : null
}
return uni.downloadFile(http.beforeRequestFilter(config));
}
export default http
可以设置全局的url访问地址(会拼接请求的url成完整的url,所以在写url时只需要"/xxx"),也可以在请求时设置具体url(以http或https开头)
可以设置全局的header,如果请求时有header参数,会加上全局的header
可以设置拦截器,有发送请求前的拦截器beforeRequestFilter,参数是包含已经拼接完的url和header的请求参数,注意要返回;执行成功回调函数前的拦截器beforeResponseFilter,参数是回调成功函数的参数,注意要返回;执行成功回调函数后的拦截器afterResponseFilter,参数为成功回调函数的返回值。
具体例子
my.js
import http from './http'
const AUTH_TOKEN = "X-Auth-Token";
http.setBaseUrl("http://localhost:8081");
http.header['comp'] = "cjx913"
if (uni.getStorageSync(AUTH_TOKEN)) {
http.header[AUTH_TOKEN] = uni.getStorageSync(AUTH_TOKEN);
}
http.beforeResponseFilter = function (res) {
//X-Auth-Token
if (res.header) {
var respXAuthToken = res.header[AUTH_TOKEN.toLocaleLowerCase()];
if (respXAuthToken) {
uni.setStorageSync(AUTH_TOKEN, respXAuthToken);
http.header[AUTH_TOKEN] = respXAuthToken;
}
}
return res;
}
let my = {
'http': http
}
export default my
main.js
import Vue from 'vue'
import App from './App'
Vue.config.productionTip = true
App.mpType = 'app'
import fly from './fly/fly'
Vue.prototype.$fly = fly
import my from './my/my'
var http = my.http;
Vue.prototype.$http = http
import store from './store'
Vue.prototype.$store = store
const app = new Vue({
...App
})
app.$mount()
index.js
<script>
export default {
data() {
return {
title: 'Hello',
name:'cjx913'
}
},
onLoad() {
},
methods: {
session:function(){
// this.$fly.get('/session')
// .then(function (response) {
// console.log("hello");
// console.log(response.data);
// console.log(response);
// })
// .catch(function (error) {
// console.log(error);
// });
// this.$http.request({
// url:"session",
// success:(res)=>{
// console.log(res);
// }
// })
// this.$http.get("/session",function(res){
// console.log(res);
// }
// )
this.$http.get("/session",{
success:function(res){
console.log(res);
}
}
)
}
}
}
</script>
上述是简单设置baseUrl,header和通过拦截器拦截response的X-Auth-Token,并让请求带上X-Auth-Token
---------------------
作者:
梦缠绕的时候
时间:
2019-7-3 14:35
任何问题欢迎在品论去留言或者联系学姐哟
作者:
梦缠绕的时候
时间:
2019-7-3 14:35
DKA-2018
作者:
晨大喵
时间:
2019-7-17 11:48
感谢分享~~
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2