In recent years, with the gradual maturity of Web development, the architecture design of front and back end separation is more and more recognized by many developers, so that the front end and back end can focus on their respective functions, reduce communication costs and improve development efficiency.

In the development model of front – and back-end separation, front – and back-end engineers can work in parallel. When the front-end interface needs to display the data, the back-end corresponding interface has not completed the development of the situation, need a data source to ensure the front-end work smoothly.

In today’s article, we’ll cover several common approaches and their problems, and propose a quick solution to cross-domain and proxy mocks based on HTTP request interception.

Common methods and problems

Requesting the Mock server

The most common approach is to maintain a mock server that provides static data (called mock data) that the front end asks the mock server for, but this static data maintenance is not easy.

Request AMP

A better idea is to have a mock server that automatically generates data based on the interface definition, called AMP (API Manage Platform), to which the front end requests data.

In this scenario, if some interfaces have already been developed, the front-end needs to manually modify the code to set the request address for the different interfaces. This approach becomes very inefficient when the number of interfaces is large. As a result, AMP will typically also provide proxy functionality, meaning that the front end will still request AMP, and the AMP will decide whether to return mock data depending on the interface completion, or to proxy the request again to the real business server for data and return.

However, the problem of this scheme is that when the interface requiring role permission authentication is involved, the browser will cache cookies after user information is entered in login. When accessing the interface with the same domain name as the login, the browser will automatically carry cookies, and the server will parse the cookies and obtain interface data corresponding to the permission after authentication. The front-end usually starts the server locally for development. When the interface of the business server is developed, then the method of requesting AMP is used to switch the interface data, and the cross-domain situation will occur.

Since the browser’s security mechanism determines that cookies cannot be carried across domains and cannot be read by code, passing cookies across domains through code is not feasible, and existing solutions are not perfect:

  • If the simulated login function is added to AMP, the corresponding data will be returned because the permissions of all interfaces are fixed and cannot be adjusted to the fact that an interface has different permissions for different roles. In addition, once the authentication interface function changes or becomes invalid, the proxy function of AMP needs to be rewritten and modified, which costs a lot.

  • If the browser plug-in is used to save login information and provide proxy, it needs to be compatible with different browsers, and the cost is too high.

To solve the above technical problems, this paper proposes a cross-browser and front-end implementation of non-intrusive business code proxy method.

Http-based request interception

Implement front-end interface proxy

The front-end interface is realized based on HTTP request interception, which realizes the switch between mock data before and after interface development and real data of business server from a lower-level perspective, and solves the problem of cross-domain permission information that cannot be carried by HTTP request through AMP proxy to business server in the existing technology. A technical problem that caused the request data to not be returned according to role permissions.

Key innovations

  1. Implement intercepting proxies at a lower level based on the XMLHttpRequest and Fetch APIS, regardless of the prevailing browser types and JavaScript dependent tool libraries;

  2. In the front end of the realization of proxy, retain the login information, no need to deal with additional authentication issues;

  3. Provides a quick implementation and pluggable use mode.

Overall, this solution provides a quick request proxy approach that runs in a front-end browser and is independent of the browser type.

Design ideas

Web front-end development generally uses JavaScript language, and HTTP requests in the browser environment are implemented based on Fetch API or XMLHttpRequest API (requests based on the former are remembered as XHR, and the latter as Fetch). The same is true of major Javascript open source libraries such as Axios and Request. Therefore, our solution is to implement the front-end proxy function by intercepting XHR or FETCH at the bottom level according to certain judgment logic.

implementation

First, repackage the native XMLHttpRequest API and Fetch API in the browser environment. The idea is to save the two native apis, add them to each repackaged API of the same name (called the new API), write the methods and properties of the new API with the same name as those of the native API, Add the ApiProxy logic to the methods of the same name that carry the request parameters (such as Open and Send below), and open up a configurable interface to configure the interception and proxy logic for data requested in different HTTP request formats.

The main role and workflow of ApiProxy in this process can be summarized as follows:

  1. Register interceptors. Receives and intercepts HTTP requests and parses the parameters in the request. The parameters refer to the parameters that uniquely identify the interface in AMP, such as domain name + request method (such as GET and POST) + path (such as /user in https://service.com/user).

  2. The request to send AMP is generated based on this parameter. AMP maintains real-time information about the interface stored on the Mock server and the real interface stored on the business server, including interface definitions, domain names, properties, development status, and so on.

  3. AMP queries the interface definition data on request, returning mock data generated based on the interface definition if the interface exists and its state is under development, otherwise returning specific response flags like “{code:” 200302 “} “in Figure 1.

  4. After receiving the response from AMP, Apiproxy determines whether there is a special flag and does not directly return mock data to the original request. If there is, it indicates that the back-end interface development is complete and it continues to send the original HTTP request to the back-end server to request the real data stored by the back-end server, which means that it does not do any processing to the original request.

Instead of sending HTTP requests to AMP, AMP determines whether to return mock data directly based on the request or enable the proxy to send the HTTP request to the business server based on the interface state (in this case, cross-domain access will lose the cookie carried by the browser in the original HTTP request). Instead of directly sending HTTP requests to AMP, the request is intercepted before it is formally sent, and the parameters are analyzed and sent to AMP, which feeds back the interface status. If the development is completed, the HTTP request is formally sent to the service server. Since the request is not modified but delayed, all authentication and other related information between the original request and the service server is retained, thus solving the problem that cross-domain access cannot carry cookies.

Implementation of ApiProxy under different request modes

Because the underlying design of different request methods is different, we have different encapsulation methods accordingly.

XMLHttpRequest

For XMLHttpRequest requests, the request is parsed in its open method, and the access AMP determines whether to continue sending the original request to the background server based on the response result. An XHR will only initiate an HTTP request when its send method is called. The open method cannot fetch the data passed by send, so interception occurs in SEND. First store the parameters to send the request in the send method separately, and then return it directly, making sure that the real XMLHttpRequest send method is not called first, and that the separately stored parameters generate the request to AMP, performing the AMP judgment described above.

The instance

Define an interface with the same name as the native XMLHttpRequest API, called the new XHR interface;

Rename the native XMLHttpRequest API and add it to the new XHR interface;

3. Define properties and methods in the new XHR interface with the same name as the native XMLHttpRequest API;

4. Parse the HTTP request in the open method of the same name, and get the parameters used to query the interface status in AMP (such as domain name + request method + path);

5. Intercept the original request to be sent, temporarily save the original request to be sent data in the send method of the same name, suspend the original request to be sent;

6. Request AMP with the parameters in 4 to query the status of the interface. If the interface does not exist or has been completed, the special flag will be returned. Otherwise, AMP returns mock data, which the ApiProxy returns directly to the original request.

Fetch API

For Fetch API, because it is implemented based on Promise, interception is relatively easy. It only needs to encapsulate a Promise entry in the outer layer of Fetch API, suspend the original request, parse the data request AMP and wait for the response before it initiates the Fetch request. Determine if the response has a special response code. If so, proceed with the original request; otherwise, skip the original request and return the mock data directly.

Enable the front-end proxy function

In the actual development of the front-end, you can use a packaging tool, such as Webpack, to customize a configurable plug-in, which automatically inserts the proxy interception code into the main page in the development environment, thus enabling the front-end proxy function.

summary

The front-end proxy approach proposed in this paper reduces the mock server’s (or interface management platform’s) request to the real business server by sinking the proxy responsibility to the front end, while keeping the role permissions in the front end request, further reducing the workload of the proxy, and the method of intercepting HTTP requests from the bottom. Bypassing the browser compatibility problems caused by using browser plug-ins as proxies. Finally, a package tool (such as Webpack) is provided to encapsulate this proxy method and achieve a quick plug and pull front-end proxy.

The author of this article, Nu Zhi, is a front-end development engineer of hornet’s Nest community RESEARCH and development team, mainly responsible for community management background, interface management platform development and other work.

Focus on hornet’s nest technology to find out more about what you need

Attached: Reference materials

About cross-domain:

Developer.mozilla.org/en-US/docs/…

About the XMLHTTPRequest:

Developer.mozilla.org/en-US/docs/…

About the Fetch:

[https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API