If you find it useful, please click here to see more modules
-
series
- Vue is a method for mobile Hybrid development and data transfer between clients
- Vue page state is a method of maintaining data transfer between pages
- Vue front-end application is a method of identity authentication permission control
- Vue is a way to reduce boilerplate code that interacts with the server
Click to visit demo
Sweep the code to access
util-http.js
Util-http. js is an Ajax module rewrapped against AXIos.
The module encapsulates AXIOS in order to reduce the workload of developers, simplify the interaction with server and client (JSBridge proxy request), and cooperate with login-state-checke.js module for identity authentication permission control.
Why do we need to encapsulate axios, because we want to do when the plug-in has experienced several projects, regardless of whether Taiwan before and after separation or whether the server is RESTFull type service, at the time of sending a request and process the request, for an enterprise application (or simple) there are more or less boilerplate code, In the process of practice, we take the sample code step by step away from the business, making it easier for developers to focus on the business itself, thus improving the development efficiency and avoiding some unnecessary errors. This module provides the following abstractions:
- Helped us handle most of the business-level errors. What is a business-level error? Because much of the data returned by the back end is not strictly RESTFull results, the concern here is that many services do not identify a request error with a status code that is not 200 in the HTTP specification, but rather have custom error codes that provide an impulse for uniform business error handling. It would be easy, of course, to add a uniform misjudgment of canonical form to this
- Help us for special request broker, because of the added a layer, we can do a lot of things, here we can make Ajax programming of Ajax, namely in the mobile application development, because of cross-domain and WebView Ajax requests are difficult to configure SSL encryption certificate for data two requirements, we can make a request is sent to the client, Then the client proxy front-end completes the sending of the request, which involves the interaction between the front-end and the client, namely JSBridge interaction. We already have a set of Android-ViewPlus, an Android hybrid client development library, to solve the JSBridge client interaction process. So here we can simply add this layer in the middle to fulfill these two requirements
- About matching the login – state – check. Js authentication access control module, you can view the current module accessRules. SessionTimeOut and accessRules onSessionTimeOut, because session real control is commonly in the background, Therefore, if the session or token in the background expires, the server will definitely return an error response, so the current module through the above two accessRules configuration, so that the application can intercept this opportunity, and before notifying the application, Cleared the plug-in login – state – check. Js login module maintenance condition: loginStateCheckInstall. ModifyLoginState (false)
The following interfaces may relate to the description of the data returned by the server, but let’s assume the basic server response data format.
Since the server data needs to describe whether the business succeeds and why the business fails, let’s agree on the structure of the data returned by the server.
In any case, the JSON data in the body returned by the server must be an object, using code to return the business state, data to return the actual data that the client is requesting, and Message to return a message indicating a business failure. If the value of code is 1, the service succeeds; if the value of code is other, the service fails. The data can be a {} | []. It is important to note that some servers will also use httpCode as a business state code. This is also true, and the encapsulation principle is the same as in this article.
The structure of the data returned by the server should be:
{" code ": [1 |" other string, such as: session_timeout_err] ", "data" : [{} | []], "message" : "error message | correct message"}Copy the code
The sample
Browse online examples
<template> <div id="UtilHttp"> <group title=" ajaxmixin-get request "label-width="15em"> <box gap="10px 10px"> < X-button @click.native="doGet" :disabled="doGetBtnState"> Use $vp#ajaxMixin to send GET requests </x-button> </box> </group> <group Title =" ajaxmixin-post request "label-width="15em"> <box gap="10px 10px"> < x-button@click. native="doPost" </x-button> </box> </group> <group title="ajaxAll request" <p class="hint-msg"> <p class="hint-msg"> But the application can call '$vp#$vp.onParseserverresp (Response)' to invoke the uniform business level error interface to follow up on the judgment according to its own needs </p> < [email protected]. stop="doAjaxAll" </x-button> </box> </group> <group title=" ajaxmixin-native request" <span class=" hint-msG-warn "> <span class="hint-msg-warn"> <span class="hint-msg-warn"> </span><br/> < x-button@click. native="doHttpNative" :disabled="doHttpNativeBtnState"> </x-button> </box> </group> </div> </template> <script type="text/ecmascript-6"> import demoMixin from './demo-mixin' import _ from 'lodash' export default { mixins: [demoMixin], data() { return { ajaxAllBtnState: false, doGetBtnState: false, doPostBtnState: false, doCORSBtnState: false, doHttpNativeBtnState: false } }, methods: { doGet() { this.doGetBtnState = true this.$vp .ajaxMixin('TIMESTAMP', { mode: }). Then (data => {this.doGetBtnState = false this.$vp.uiDialog(data, {title: 'request successful, response result ', showCode: true } ) }) .catch(resp => { console.log(resp) this.doGetBtnState = false }) }, doPost() { this.doPostBtnState = true this.$vp .ajaxMixin('LOGIN') .then(data => { this.doPostBtnState = false This.$vp.uiDialog(data, {title: 'request successful, response result ', showCode: true } ) }) .catch(resp => { this.doPostBtnState = false }) }, doAjaxAll() { this.ajaxAllBtnState = true this.$vp .ajaxAll([ { url: 'ALL1', mode: 'GET' }, { url: 'ALL2', mode: 'GET'}]). Then (resArr => {this.ajaxAllBtnState = false) const res = _. Map (resArr, (item) => {return item.data}) this.$vp.uiDialog(res, {title: 'request successful, response result ', showCode: true }) }) }, doHttpNative() { this.doHttpNativeBtnState = true this.$vp .ajaxMixin('TIMESTAMP', { mode: 'NATIVE'}). Then (res => {this.$vp.uiDialog(res, {title: 'request successful, response result ', showCode: True}) enclosing doHttpNativeBtnState = false}). The catch ((err) = > {this. $vp. UiDialog (err, {title: 'request fails, the result, showCode: true }) this.doHttpNativeBtnState = false }) } } </script>Copy the code
Example Required configurations:
Vue.use(ViewPlus, { //... UtilHttp: {baseURL: 'http://localhost:7000', // data key here, see mock Server jSONp output configuration dataKey: 'data', statusCodeKey: 'code', statusCode: '1', msgKey: 'msg', needBase64DecodeMsg: false, loading(loadingHintText) { this.uiLoading(loadingHintText) }, hideLoading() { this.uiHideLoading() }, ErrDialog (content = 'error message not defined ') {this.dialog(content) return this}, accessRules: {sessionTimeOut: ['role.invalid_user', 'validation.user.force.logout.exception'], OnSessionTimeOut (response) {this.dialog(' onSessionTimeOut callback: ${response.msg} ', {title: 'callback notification'})}, unauthorized: [' core_ERROR_UNAUTHORIZED '], onUnauthorized(response) {this.dialog(' onUnauthorized callback ${response. MSG} ', {title: 'Callback notification'})}}}})Copy the code
configuration
For the configuration of axios, see axios#config.timeout, which generally indicates that axios#config.timeout belongs to the axios configuration
baseURL *
/** * [optional] 'baseURL' automatically precedes' url 'unless' url 'is an absolute URL. It can facilitate passing relative urls * <p> * to axios instance methods by setting a 'baseURL' [axios#config.timeout](https://github.com/axios/axios#request-config) */ baseURL = {String}Copy the code
timeout
/** * [Optional] 'timeout' specifies the number of milliseconds for the request to timeout (0 indicates no timeout). If the request takes longer than timeout, The request will be interrupt * < p > * [axios# config. The timeout] (https://github.com/axios/axios#request-config) * / timeout = 6000Copy the code
params
/** * [Optional] 'params' is the URL parameter to be sent with the request must be a plain object or URLSearchParams object * <p> * [axios#config.timeout](https://github.com/axios/axios#request-config) */ params = nullCopy the code
headers
/ * * * [optional] ` headers ` is about to be sent by the custom request header * < p > * [axios# config. The timeout] (https://github.com/axios/axios#request-config) * / headers = nullCopy the code
withCredentials
/ * * * said cross-domain request whether need to use the credentials * < p > * [axios# config. The timeout] * / withCredentials = (https://github.com/axios/axios#request-config) falseCopy the code
mode
/ * * * the default request method optional 】 【 【 'GET' | 'POST' | 'NATIVE'] * < p > * note: If the majority of transactions across the application require the ** client proxy to forward requests (involving front-end and client interactions, i.e. JSBridge interactions, we already have an Android-ViewPlus hybrid android client development library that addresses JSBridge client interactions) **, $vp#ajaxMixin = 'NATIVE'; $vp#ajaxMixin = 'NATIVE'; $vp# ajaxmixin. mode = 'POST'Copy the code
onSendAjaxParamsHandle
/** * '$vp#onSendAjaxParamsHandle(url, params, mode)=>{}' * <p> * If this function is configured, it does not need to be handled by the plugin (currently the plugin only handles POST requests with 'qs.stringify(Params)') */ onSendAjaxParamsHandle = nullCopy the code
statusCodeKey [*]
UtilHttp#onParseServerResp = UtilHttp#onParseServerResp = UtilHttp#onParseServerResp = UtilHttp#onParseServerResp = UtilHttp#onParseServerResp {code: [1] | 0}, code back to the business state of use, here is configured to ` code ` * / statusCodeKey = 'code'Copy the code
statusCode [*]
HttpUtil# onParseServerResp: httpUtil#onParseServerResp: httpUtil#onParseServerResp: httpUtil#onParseServerResp: {code: [1] | 0}, use code to return to the business state, one identified as a * * * * success, there is configured to ` 1 ` * / statusCode = '1'Copy the code
onSendAjaxRespHandle
/** * [Optional] '$vp#onSendAjaxRespHandle(response)=>{}' * < P > ** after the return of the ** preprocessing response result object **, the unified business judgment and other subsequent processing logic */ onSendAjaxRespHandle = NULLCopy the code
onParseServerResp [*]
/ * * * [optional] ` $vp# onParseServerResp (response) = > (true | false] ` * application manually for the success of the business logic judgment, the callback function, if the configuration of the callback function, You do not need to configure ` UtilHttp# statusCode && UtilHttp# statusCodeKey ` * < p > * return true identity request success | false identification errors, Plug-in will find returns the response data of the ` UtilHttp# [msgKey | errMsgKey] ` corresponding messages, call ` UtilHttp# errDialog ` feedback to the user * / onParseServerResp = nullCopy the code
onSendAjaxRespErr
/** * [optional] '$vp#onSendAjaxRespErr(Response)' * this function is called when a business-level error has occurred. If this function returns true, the application has handled the requested error. Otherwise, the plugin will handle it. Plug-in will find returns the response data of the ` UtilHttp# [msgKey | errMsgKey] ` corresponding messages, call ` UtilHttp# errDialog ` feedback to the user * / onSendAjaxRespErr = nullCopy the code
errCodeKey
/** * [optional] UtilHttp#statusCode (optional, UtilHttp#statusCode) * <p> * If the server returns a key for the error code: | 0 {code: [1], err_code: 'auth_err}, with err_code return an error code, here is configured to ` err_code `, no plug-ins will read ` code ` as error code, * * and according to the error code do [session timeout | insufficient permissions | invalid pop-up error dialog] the judgment of the * * * / errCodeKey = ' 'Copy the code
noNeedDialogHandlerErr
/ * * * [optional] don't need the plugin when business level error pop up error message rules set (using array format), configure the background response returned ` UtilHttp# [errCodeKey | statusCode] ` corresponding error code * < p > * if the server returns: | 0 {code: [1], err_code: 'auth_err}, ` auth_err ` can as configuration items here: ['auth_err'], when the plugin detects that the current error code is in this collection, no error message will pop up */ noNeedDialogHandlerErr = nullCopy the code
accessRules
/** * access control rules */ accessRules: {Copy the code
accessRules.sessionTimeOut
/ * * * [optional] session timeout rule sets (using array format), when business level error, in view of the session timeout * * * * the background when the returned ` UtilHttp# [errCodeKey | statusCode] ` corresponding error code to match * < p > * if the server returns: | 0 {code: [1], err_code: 'session_time_out}, ` session_time_out ` can as configuration items here: ['session_time_out'], which identifies an expired session. When the plugin detects an expired session code in the collection, * will invoke the 'UtilHttp#onSessionTimeOut' callback function to notify the application for re-login, etc. Because detecting whether a session times out is triggered only when a request is sent to the background interface that requires authentication. . Second, plug-in invokes ` loginStateCheck modifyLoginState ` * remove plugins active maintenance state and persistent login information to log in, See interface */ sessionTimeOut = NULL for details in 'login-state-check.js' moduleCopy the code
accessRules.onSessionTimeOut
/** * $vp#onSessionTimeOut(response) For session timeout * * * * the background when the returned ` UtilHttp# [errCodeKey | statusCode] ` corresponding error judgment is the callback for when session timeout * / onSessionTimeOut = nullCopy the code
accessRules.unauthorized
/ * * * "optional" insufficient permissions set rules (using array format), when business level error, in view of the session timeout * * * * the background when the returned ` UtilHttp# [errCodeKey | statusCode] ` corresponding error code to match * < p > * if the server returns: | 0 {code: [1], err_code: 'auth_fail}, ` auth_fail ` can as configuration items here: ['auth_fail'], which indicates that this is an unauthorized error. When the plug-in detects that the current error code is in this collection, * calls the 'UtilHttp#onUnauthorized' callback to notify the application, */ Unauthorized = NULL */ Unauthorized = NULLCopy the code
accessRules.onUnauthorized
/** * [Optional] $vp#onUnauthorized(response) For the session timeout * * * * the background when the returned ` UtilHttp# [errCodeKey | statusCode] ` corresponding error code to match * / onUnauthorized = nullCopy the code
dataKey
/** * [optional] The json object returned by the server stores the key of the object (business status code, error message, data that needs to be returned to the front end), some background interfaces have it, some do not * {String} * <p> * | 0 {code: [1], rdata: {}}, with rdata returns the actual transaction data, here is configured to ` rdata `, otherwise don't have to configure * < p > * if there is the configuration, so after the request is successful, The value of server response.datakey will be returned in 'Promise#resolve', UtilHttp#errInfoOutDataObj 'will be discriminated against */ dataKey = 'data'Copy the code
msgKey
/** * UtilHttp#errDialog, UtilHttp#errDialog, UtilHttp#errDialog, UtilHttp#errDialog, UtilHttp#errDialog, UtilHttp#errDialog | 0 {code: [1], MSG: 'you have no right to access the interface'}, use MSG returns the actual transaction data in the error message, here is configured to ` MSG ` * / msgKey = 'MSG'Copy the code
errMsgKey
/** * [optional] UtilHttp#msgKey (optional, UtilHttp#msgKey) * <p> * If the server returns: | 0 {code: [1], errmsg: 'you have no right to access the interface'}, with errmsg returns the actual transaction data of error messages, here is configured to ` errmsg `, otherwise don't configuration, ** Plug-in will try to find 'UtilHttp#msgKey' ** */ errMsgKey = 'errmsg'Copy the code
errDialog [*]
/ * * * ` UtilHttp# errDialog (errMsg) ` * when send/request error | born business level error is invoked, this convenient application adaptation in line with their own UI components * / errDialog = window. The alertCopy the code
errInfoOutDataObj
/** * [Optional] Whether the error message returned by the server is not in the object corresponding to 'UtilHttp#dataKey' * <p> * | 0 {code: [1], rdata: {MSG: 'you have no right to access the interface'}}, with rdata returns the actual transaction data, MSG id error message, here is configured to ` false ` * < p > * if the server returns: | 0 {code: [1], rdata: {}, MSG: 'you have no right to access the interface'}, with rdata returns the actual transaction data, MSG id error message, here is configured to ` true ` * / errInfoOutDataObj = falseCopy the code
onReqErrPaserMsg
/** * [Optional] 'UtilHttp#onReqErrPaserMsg(Response)=>{string}' * UtilHttp#onReqErrPaserMsg(Response)=>{string} '* UtilHttp#onReqErrPaserMsg(Response)=>{string}' * UtilHttp#onReqErrPaserMsg(Response)=>{string} ' * <p> * If a callback returns a non-null character, the application processes the error message. Otherwise, the error result parsed by default is displayed. */ onReqErrPaserMsg = nullCopy the code
defShowLoading [*]
/** * [Optional] Whether to enable loading * <p> * When sending a request The loading UI of Ajax should be configured with both 'utilHttp#loading' and 'utilHttp#hideLoading' interfaces, so that the application can fit its OWN UI components */ defShowLoading = falseCopy the code
loading [*]
/** * $vp#loading(hintText) * <p> * ] is used to enable the application to implement its own loading UI, so that the application can easily adapt its own UI components */ loading = nullCopy the code
hideLoading [*]
/** * $vp#hideLoading() * <p> But this method is also triggered */ hideLoading = nullCopy the code
ajaxMixin
/** * JsBridge proxy request configuration */ ajaxMixin: {Copy the code
ajaxMixin.eventName
/** * eventName = 'AjaxEvent'; /** eventName = 'AjaxEvent';Copy the code
ajaxMixin.actionName
/** * actionName of 'command' when sending JSBridge request, refer to 'js-bridge-context.js' module about command configuration for client interaction */ actionName = 'sendOriginalRequest'Copy the code
onPageTo
$vp#pageTo(n) : $vp#pageTo(n) : $vp#pageTo(n) : $vp#pageTo(n)Copy the code
onPageReplace
$vp#pageReplace(location); /* / onPageReplace = nullCopy the code
onPageNext
$vp#pageNext(location) : $vp#pageNext(location)Copy the code
onPageGoBack
$vp#pageGoBack() : $vp#pageGoBack() : $vp#pageGoBack()Copy the code
onPageHref
$vp#pageHref = $vp#pageHref = $vp#pageHref = $vp#pageHref = $vp#pageHref = $vp#pageHrefCopy the code
API interface
getAjaxInstance
Returns {*} */ getAjaxInstance()Copy the code
ajaxUpdateInstance
@param options */ ajaxUpdateInstance(options)Copy the code
onParseServerResp
$vp.onParseServerResp(response) $vp.onParseServerResp(response) * <p> The application can call '$vp#$vp.onParseServerResp(Response)' to invoke the unified Business level error interface for subsequent processing of the judgment based on its own requirements * @returns {Boolean} true to indicate that the business level is successful. OnParseServerResp (response)Copy the code
ajaxAll
@param {Array} [ajaxArr=[]] Each item can be configured as an argument to 'UtilHttp#ajaxMixin', Exclude 'showLoading and loadingHintText' * @param {Boolean} [showLoading=false] The 'UtilHttp#loading(loadingHintText)' configuration will be invoked, Default is' UtilHttp#defShowLoading 'configuration (true) * @param {String} [loadingHintText=' loading...'] When loading is required, Note that a two-dimensional array is returned, and each item is an AXIos default response result, which needs to be processed manually. For example: * const res = _.map(resArr, (item) => {* return item.data *}) * retrieve the response for each transaction * @returns {Promise<any>} */ ajaxAll(ajaxArr = [], {showLoading = _defShowLoading, loadingHintText = 'Loading... '} = {})Copy the code
ajaxMixin
/** * ajaxMixin(url[, Config]) * support common Ajax GET/POST (default) requests and client bridge access * @ param {String} [url = undefined] transaction code | full request url * @ param {Object} [params={}] Request parameters Support method [' GET '|' POST '|' NATIVE '] * @ param {Object} [axiosOptions = {}] axios options * @ param {Boolean} [showLoading=false] If loading UI is displayed, 'UtilHttp#loading(loadingHintText)' configuration will be invoked, Default is' UtilHttp#defShowLoading 'configuration (true) * @param {String} [loadingHintText=' loading...'] When loading is required, * @param {Boolean} [needHandlerErr=true] Whether the default error handling is required, so as to bypass the business processing logic provided by the plug-in when the uniform business logic processing is not required for some ** transactions. In addition can also be configured ` $vp# onSendAjaxRespErr ` for unified business processing application unified pre-processing * * * * * @ param {String} [mode = 'POST'] request method [' GET '|' POST '| 'NATIVE' 】, By default, the 'utilHttp#mode = POST' parameter passed during initial configuration is used to assign the initial value * @returns {Promise} */ ajaxMixin(URL, {params = {}, axiosOptions = {}, ShowLoading = _defShowLoading, loadingHintText = 'loading... ', needHandlerErr = true, mode = _defMode } = {})Copy the code
ajaxGet
/ send a GET request * * * * < p > * bottom to ` $vp# ajaxMixin ` processing * * @ param {String} [url = undefined] transaction code | full request url * @ param {Object} [params={}] Request parameters Support method [' GET '|' POST '|' NATIVE '] * @ param {Object} [axiosOptions = {}] axios options * @ param {Boolean} [showLoading=false] If loading UI is displayed, 'UtilHttp#loading(loadingHintText)' configuration will be invoked, Default is' UtilHttp#defShowLoading 'configuration (true) * @param {String} [loadingHintText=' loading...'] When loading is required, * @param {Boolean} [needHandlerErr=true] Whether the default error handling is required, so as to bypass the business processing logic provided by the plug-in when the uniform business logic processing is not required for some ** transactions. Returns {Promise} */ ajaxGet(url, {params = {}, AxiosOptions = {}, showLoading = _defShowLoading, loadingHintText = 'Loading... ', needHandlerErr = true } = {})Copy the code
ajaxPost
/ * * * to send a POST request * < p > * bottom to a ` $vp# ajaxMixin ` processing * * @ param {String} [url = undefined] transaction code | full request url * @ param {Object} [params={}] Request parameters Support method [' GET '|' POST '|' NATIVE '] * @ param {Object} [axiosOptions = {}] axios options * @ param {Boolean} [showLoading=false] If loading UI is displayed, 'UtilHttp#loading(loadingHintText)' configuration will be invoked, Default is' UtilHttp#defShowLoading 'configuration (true) * @param {String} [loadingHintText=' loading...'] When loading is required, * @param {Boolean} [needHandlerErr=true] Whether the default error handling is required, so as to bypass the business processing logic provided by the plug-in when the uniform business logic processing is not required for some ** transactions. In addition can also be configured ` $vp# onSendAjaxRespErr ` for unified business processing application unified pre-processing * * * * * @ returns {* | Promise} * / ajaxPost (url, {params = {}, AxiosOptions = {}, showLoading = _defShowLoading, loadingHintText = 'Loading... ', needHandlerErr = true } = {})Copy the code
pageHref
/** * to jump a page through 'window.location.href' * <p> * to notify the 'http# onPageHref' hook function, @param url @returns {$vp} */ pageHref(url)Copy the code
pageTo(n = -1)
/** * utilHttp#onPageTo(n, Router) 'hook function is notified before jump, if * @returns {$vp} */ pageTo(n)Copy the code
pageGoBack()
/** * A single page rollback (based on the Router) * <p> * will be notified before jumping to the 'utilHttp#onPageGoBack(Router)' hook function, if configured * @returns {$vp} */ pageGoBack()Copy the code
pageNext(location = {path: ‘/’})
/** * the 'utilHttp#onPageNext(location, Router)' hook function is notified before a page navigation (based on the Router) * <p> * * @param location * @returns {plugin} */ pageNext(location)Copy the code
pageNext
/** * page navigation (based on Router), utilHttp#onPageReplace(location, Router) 'hook function is notified before removing a previous page * <p> *, * @param location * @returns {plugin} */ pageReplace(location = {path: '/'})Copy the code