Twenty minutes package, the implementation of HTTP interaction between the front and back of an app

Time:2020-11-16

In the process of react native development, almost all apps need to use HTTP requests, so the encapsulation of fetch is essential. Because the request parameters, parsing rules and token mechanism of different apps are completely different, in most app development, the implementation of HTTP requests in the front and back platforms is encapsulated by developers themselves.

How long does it take to encapsulate a background HTTP request implementation?

Some people may say that it will take one hour, three or five hours or even longer, or they may say that we should encapsulate it in this way and wait until the demand is not satisfied.

The time spent in one hour is not necessarily short, and the time spent in 3 or 5 is not necessarily long. It depends on the complexity of the front-end and background interaction and the degree of encapsulation of the interaction implementation by developers.

Then we have a question here. What is the encapsulation of the HTTP request of the app? What do we need to do? Can the interface request of the app be simpler, easier to use and more flexible? In my opinion, this “package” is mainly divided into two parts:

  1. Data exchange level encapsulation, namely:

    • Realize the intercommunication between the front and background, and support the data exchange type and format required by the server
    • The caller can freely set the header, params and other parameters of the request. According to different settings, the program can also ensure that the request can be sent to the server correctly and return the corresponding results
    • Support timeout, log printing and other basic functions
  2. Encapsulation of business logic level, namely:

    • Input parameter: parameter processing of header and params in the common part to avoid unnecessary interface independent parameters in specific interface request
    • Output parameter: do a layer of basic parsing and processing for the data returned from the background according to the agreed rules, so as to avoid some meaningless operations when parsing the specific interface data

In terms of investment time:
The first part basically takes more than 80% of developers’ time to package
The second part may take less than 20% of the time[based on this calculation, according to the above 1 hour packaging time, the time used in the logical packaging part is about 12 minutes]

Let’s take a look back. Does the data exchange encapsulation in the first part involve specific business logic? The answer is: No.

Since there is no such package, why don’t we hand over the first part of the package to a third-party framework? We only need to do the second part of the package. Is there such a third-party framework?

The answer is: Yes, the react native easy app can encapsulate the data exchange between the front and back platforms. Through this open source library, we only need to implement the encapsulation involving the [app business logic] level.


In order to verify the practicability of react native easy app, we first conceive a business logic level encapsulation requirement

  1. The common headers parameters of the request interface are:

    • Version, channelcode, model, platform (all interfaces)
    • Accesstoken, refreshtoken, CustomerID (additional after login)
  2. The common params parameters of the request interface are:

    • CustomerID (additional after login)
  3. An example of the data structure returned from the background is as follows:
    { data: {}, successful:1, msg: ‘request msg’, code: ‘xxx’}
  4. When the request status code is 503, it means that the accesstoken has expired. When the accesstoken is expired, it is necessary to obtain a new accesstoken and refresh the interface that failed the request due to the expiration of the accesstoken

    1. Accesstoken and refreshtoken are returned in the response headers after successful login.

For the above business logic level requirements, let’s see what we can do with react native easy app.

XHttpConfig().initHttpLogOn(true)
    .initHeaderSetFunc((headers) => {
        headers['model'] = 'xiao mi';
        headers['version'] = '1.0.0';
        headers['platform'] = Platform.OS;
        headers['channelCode'] = 'channelOfficial';
        if (isLogin()) {
            headers['customerId'] = RNStorage.customerId;
            headers['accessToken'] = RNStorage.accessToken;
            headers['refreshToken'] = RNStorage.refreshToken;
        }
    })
    .initParamSetFunc(params => {
        if (isLogin()) {
            params['customerId'] = RNStorage.customerId;
        }
    })
    .initParseDataFunc((result, request, callback) => {
        let {success, json, message, status, response} = result;
        If (status = = = 503) {// accesstoken expiration tag
            this.refreshToken(request, callback);
        } else {
            let {data, successful, msg, code} = json;
            callback(success && successful === 1, data || {}, msg || message, code, response);
        }
    });

The implementation of re request of accesstoken and refresh of failed interface:

refreshToken = (request, callback) => {
    if (global.hasQueryToken) {
        global.tokenExpiredList.push({request, callback});
    } else {
        global.hasQueryToken = true;
        global.tokenExpiredList = [{request, callback}];
        const refreshUrl = `${RNStorage.baseUrl}api/refreshToken?refreshToken=${RNStorage.refreshToken}`;
        fetch(refreshUrl).then(resp => {
            resp.json().then(({successful, data: {accessToken}}) => {
                If (successful = = = 1) {// get the new accesstoken
                    RNStorage.accessToken = accessToken;
                    global.tokenExpiredList.map(({request, callback}) => {
                        request.resendRequest(request, callback);
                    });
                    global.tokenExpiredList = [];
                } else {
                    console.log ('token expired, log out ');
                }
            });
        }).catch(err => {
            console.log ('token expired, log out ');
        }).finally(() => {
            global.hasQueryToken = false;
        });
    }
};

In this way, the logical level encapsulation of the currently conceived app is realized(the implementation of the above code is about 70 lines, which may take more than 20 minutes, but is it a lot of time saved compared with the previous zero open encapsulation?)Is it clear. Of course, this is just a code fragment. Without actual operation, there is no way to prove that the above code implementation is actually effective.


For demonstration, usereact native init HttpTestDemoCreate an RN project: example project: httptestdemo modify and delete unnecessary layout or resources. The result is as follows:

Twenty minutes package, the implementation of HTTP interaction between the front and back of an app

Suppose there are three interfaces: API / login, API / userinfo, and API / refreshtoken(To save time, the interfaces are replaced by JSON files

  • API / login has two required parameters: [username, userpass]; the request content type is: application / x-www-form-urlencoded; post request
  • API / userinfo has no parameters; the request content type is application / JSON; get request
  • API / refreshtoken must have parameter refreshtoken; the request content type is application / JSON; get request

https://react-native-easy-app…
https://react-native-easy-app…
https://react-native-easy-app…

  1. According to the instructions of react native easy app, install the Library:npm install react-native-easy-app --save
  2. Define a persistent object to save accesstoken, CustomerID and other parameters
Export const rnstorage = {// persistent data list
    CustomerID: defined, // customer ID
    accessToken: undefined,//OAuth2.0 accessToken
    refreshToken: undefined,//OAuth2.0 refreshToken
    baseUrl: undefined,
    userInfo: undefined,
    hasLogin: false,
};

3. Call the initialization operation of rnstorage during the page construction method; after initialization, call HTTP to request the initialization method of business logic layer of xhttpconfig, which is completed, and now you can call the interface.

  • Call the login interface: (because the form of JSON file can only use get request)
import { XHttp } from 'react-native-easy-app';

login = () => {
    let params = {userName: 'zhangsan', userPass: '123456a'};
    XHttp().url('api/login').param(params).formEncoded().get((success, json, message, status, resonse) => {
        if (success) {
            if (resonse.headers && resonse.headers.map) {
                RNStorage.accessToken = resonse.headers.map['x-oss-meta-accesstoken'];
                RNStorage.refreshToken = resonse.headers.map['x-oss-meta-refreshtoken'];
            }
            RNStorage.customerId = json.customerId;
            RNStorage.hasLogin = true;
            this.setState({data: JSON.stringify(json)});
        } else {
            console.log ('failed ', message);
        }
    });
};

Call the interface. Through the log function of the framework, we can see that the parameters of the spelling are spliced, and the token is also obtained from the header

Twenty minutes package, the implementation of HTTP interaction between the front and back of an app

  • Call to obtain user’s personal information interface:
import { XHttp } from 'react-native-easy-app';

queryUserInfo = () => {
    XHttp().url('api/userInfo').formJson().get((success, json, message) => {
        if (success) {
            RNStorage.userInfo = json;
            this.setState({data: JSON.stringify(json)});
        } else {
            console.log ('failed ', message);
        }
    });
};

Call the interface. Through the log function of the framework, you can see that the accesstoken and refreshtoken are correctly spliced.

Twenty minutes package, the implementation of HTTP interaction between the front and back of an app

Since there is no suitable server, the token expiration will not be demonstrated. As long as the interface requesting the refreshtoken is normal, the request will not be a problem.

So far, the encapsulation of a complete app [business logic] level has been fully implemented. From the configuration of HTTP requests to the re request of refreshtoken to the refresh failure interface, it only takes about 70 lines of code. Is it simpler and easier than the previous fetch encapsulation from scratch, saving a lot of packaging time?

Worried about the flexibility of the framework? Please refer to react native easy app (2) fetch and react native easy app open source library not only encapsulates HTTP requests, but also has more functions. Interested students can view other articles in this column, and you will surely get more.

Link to current sample project: httptestdemo

If you have any questions, welcome to scan the code to join the RN technology QQ communication group

Twenty minutes package, the implementation of HTTP interaction between the front and back of an app

Recommended Today

Regular expression sharing for checking primes

This regular expression is shown as follows: Regular expressions for checking prime numbers or not To use this positive regular expression, you need to convert the natural number into multiple 1 strings. For example, 2 should be written as “11”, 3 should be written as “111”, 17 should be written as “11111111111”. This kind of […]