2020-12-04

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









原文转载:http://www.shaoqun.com/a/494919.html

雨果网:https://www.ikjzd.com/w/1307

topia:https://www.ikjzd.com/w/2741

塔图:https://www.ikjzd.com/w/2274


http.js//封装requset,uploadFile和downloadFile请求,新增get和post请求方法lethttp={'setBaseUrl':(url)=>{if(url.charAt(url.length-1)==="/"){url=url.substr(0,url.length-1)}http.baseUrl=url;},'
易联通:易联通
cima:cima
Shopee开店:0基础小白必看必收藏!:Shopee开店:0基础小白必看必收藏!
Shopee平台对卖家惩罚积分系统开始实行:Shopee平台对卖家惩罚积分系统开始实行
亚马逊老卖家是怎样判断选品的?:亚马逊老卖家是怎样判断选品的?

No comments:

Post a Comment