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. pytest接口测试轻松入门

    通过Postman请求结果如下图: 那我们怎么用pytest进行测试呢? 在接口测试,我们要用到requests包,实现代码如下: import pytest import allure import ...

  2. 一个简单的CSS示例

    1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8" /> 5 & ...

  3. IIS本地部署局域网可随时访问的项目+mysql可局域网内访问

    开端口即可 或者以下 原理 在本机的IIS下创建一个网站,文件目录直接指向Web项目文件夹 步骤 1.项目的启动项目为web 2.在iis中创建一个新的网站(Work_TK_EIS) 文件目录为web ...

  4. Nacos(一)源码分析Nacos注册示例流程

    nacos官方地址:https://nacos.io/zh-cn/ 大家可以看一下nacos的中文手册以及官方源码,博主就不带领大家快速入门 了,官方文档中都有而且非常标准,比其他博客写的好多了并且还 ...

  5. 为什么线程安全的List推荐使用CopyOnWriteArrayList,而不是Vector

    注:本系列文章中用到的jdk版本均为java8 相比很多同学在刚接触Java集合的时候,线程安全的List用的一定是Vector.但是现在用到的线程安全的List一般都会用CopyOnWriteArr ...

  6. easyui中刷新列表

    <table class="crud-content-info" id="showProductDialogFormstandrad"> </ ...

  7. Eclipse中,No compiler is provided in this environment. Perhaps you are running on a JRE rather than a

    问题说明 Eclipse导入Maven项目后,执行 mvn clean install后,出现如下错误: [INFO] ---------------------------------------- ...

  8. Maven的工程类型有哪些?

    POM工程:POM工程是逻辑工程.用在父级工程或聚合工程中.用来做jar包的版本控制. JAR工程:将会打包成jar用作jar包使用.即常见的本地工程 - Java Project. WAR工程:将会 ...

  9. MySQL 标识符到底区分大小写么——官方文档告诉你

    最近在阿里云服务器上部署一个自己写的小 demo 时遇到一点问题,查看 Tomcat 日志后定位到问题出现在与数据库服务器交互的地方,执行 SQL 语句时会返回 指定列.指定名 不存在的错误.多方查证 ...

  10. 【Flutter】可滚动组件之SingleChildScrollView

    前言 SingleChildScrollView类似于Android中的ScrollView,它只能接收一个子组件. 接口描述 const SingleChildScrollView({ Key ke ...