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

uni-app开发经验分享十: 封装request请求的更多相关文章

  1. 小程序封装request请求,统一API

    程序开发中都会调用后端工程师开发的API,小程序的开发文档提供了相对实用的APIwx.request(),但是在开发的过程中,又遇到了一些问题,在小程序的项目开发时,调用的API不止一个,同一个API ...

  2. 小程序封装request请求

    //request.js var host = 'https://www.xxx.com';//请求域名 module.exports = function (type, params, method ...

  3. uni-app开发经验分享十六:发布android版App的详细过程

    开发环境 1. Android Studio下载地址:Android Studio官网 OR Android Studio中文社区 2. HBuilderX(开发工具) 3. App离线SDK下载:最 ...

  4. uni-app开发经验分享十九: uni-app对接微信小程序直播

    uni-app对接微信小程序直播 1.登录微信小程序后台-点击>设置->第三方设置->添加直播插件 2.添加直播组件后->点击<详情>      记录这两个参数直播 ...

  5. uni-app开发经验分享十八:对接第三方h5

    1.uni-app中对接第三方为了防止跳出app使用了webview <template> <view> <web-view :src="url" @ ...

  6. uni-app开发经验分享十五: uni-app 蓝牙打印功能

    最近在做uni-app项目时,遇到了需要蓝牙打印文件的功能需要制作,在网上找到了一个教程,这里分享给大家. 引入tsc.js 简单得引入到自己所需要得页面中去,本次我们只要到了标签模式,他同时还有账单 ...

  7. uni-app开发经验分享十二: Android平台应用启动时读写手机存储、访问设备信息(如IMEI)等权限策略及提示信息

    Android平台从6.0(API23)开始系统对权限的管理更加严格,所有涉及敏感权限都需要用户授权允许才能获取.因此一些应用基础业务逻辑需要的权限会在应用启动时申请,并引导用户允许. 读写手机存储权 ...

  8. uni-app开发经验分享十四:小程序超过2M限制的方法——分包加载

      起初小程序上线时,微信限制了代码包不能超过1MB,后来功能变大变成了2M了,限制大小是出于对小程序启动速度的考虑,希望用户在使用任何一款小程序时,都能获得一种"秒开"体验.但是 ...

  9. 微信小程序带cookie的request请求代码封装(小程序使用session)

    微信小程序带cookie的request请求可,以使服务端知道是同一个客户端请求. session_id会不变,从而很好的使用服务端的session. 写一个工具函数,直接导入使用即可,接口同 wx. ...

随机推荐

  1. 为什么 HashMap 的容量大小要设置为2的N次方?

    原文链接:https://www.changxuan.top/?p=1208 前两天,我在一位同学提交中看到了下面这样的一行代码,让我很是惊讶. Map<String, String> t ...

  2. 面试官: ShardingSphere 学一下吧

    文章目录 目录 一.ShardingSphere简介 二.Sharding-JDBC 2.1 Sharding-JDBC实现水平分表 2.2 Sharding-JDBC实现水平分库 2.3 Shard ...

  3. Spring Cloud Alibaba基础教程-Nacos(三)

    在Spring Cloud Alibaba基础教程-Nacos(二)当中学习了,如何使用 nacos图形化界面操作 ,使用Nacos部署集群,下面我们开始Nacos最后一篇的学习 ,如果对你有帮助,记 ...

  4. ⑦SpringCloud 实战:引入Sleuth组件,完善服务链路跟踪

    这是SpringCloud实战系列中第7篇文章,了解前面第两篇文章更有助于更好理解本文内容: ①SpringCloud 实战:引入Eureka组件,完善服务治理 ②SpringCloud 实战:引入F ...

  5. python序列(七)序列操作的常用内置函数

    1.len(列表):返回:列表中的元素个数,同样适用于元组.字典.集合.字符串等. max(列表).min(列表):返回列表中的最大或最小元素同样适用于元组.字典.集合.range对象等. sum(列 ...

  6. spark 系列之一 RDD的使用

    spark中常用的两种数据类型,一个是RDD,一个是DataFrame,本篇主要介绍RDD的一些应用场景见代码本代码的应用场景是在spark本地调试(windows环境) /** * 创建 spark ...

  7. python3使用configparser读取配置文件

    python2中的ConfigParser在python3中改成了configparser 1.配置文件格式是 [域名] k=v 2.代码示例:需要生成conf.ini配置文件如下:[config]v ...

  8. 循序渐进VUE+Element 前端应用开发(30)--- ABP后端和Vue+Element前端结合的分页排序处理

    在很多列表展示数据的场合中,大多数都会需要一个排序的处理,以方便快速查找排序所需的数据,本篇随笔介绍如何结合ABP后端和Vue+Element前端结合的分页排序处理过程. 1.Vue+Element前 ...

  9. leetcode网站中找到的关于trie树的JAVA版本介绍

    class TrieNode { // R links to node children private TrieNode[] links; private final int R = 26; pri ...

  10. [简单-剑指 Offer 53 - II. 0~n-1中缺失的数字]

    [简单-剑指 Offer 53 - II. 0-n-1中缺失的数字] 一个长度为n-1的递增排序数组中的所有数字都是唯一的,并且每个数字都在范围0-n-1之内.在范围0-n-1内的n个数字中有且只有一 ...