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

最新文章

  1. 一种简单,轻量,灵活的C#对象转Json对象的方案(续)
  2. Android 防止多次点击事件
  3. 《JS语言精粹》学习笔记 函数部分の闭包
  4. MVC验证session是否过期,在每个action执行之前验证
  5. linux常用命令-权限管理命令
  6. SLF4J环境变量配置
  7. 关于UIView(转)
  8. Swift基础使用方法(Swift开发之中的一个)
  9. CSDN蒋涛:我为什么和王峰一起创办极客帮天使基金?
  10. bzoj 1176 Mokia(CDQ分治,BIT)
  11. js下firstElementChild firstChild 以及childNodes和children方法
  12. MS Server中varchar与nvarchar的区别
  13. ASP.NET - 分页
  14. Shell 遍历字符串与参数
  15. Python内置函数(33)——int
  16. java代码之美(5)---guava之Multiset
  17. 从Redis到Codis移植实践
  18. vmware提示请卸载干净再重新安装的解决办法
  19. babel-preset-env使用介绍
  20. [转]HashMap,LinkedHashMap,TreeMap的区别

热门文章

  1. Python高级语法-私有属性-with上下文管理器(4.7.3)
  2. 关于 ReentrantLock 中锁 lock() 和解锁 unlock() 的底层原理浅析
  3. 我们是如何实现DevOps的
  4. C# 队列Queue,ConcurrentQueue,BlockingCollection 并发控制lock,Monitor,信号量Semaphore
  5. js中Tabs插件打开的标签页过多自动关闭
  6. CountDownLatch深度剖析
  7. LeetCode数组移除数组中目标元素等题目
  8. [leetcode]75.Sort Color三指针
  9. [leetcode]138. Copy List with Random Pointer复制带有随机指针的链表
  10. Java源码系列4——HashMap扩容时究竟对链表和红黑树做了什么?