Thinking and summary of front and back end docking

Time:2021-3-6

With the popularity of the front-end nodejs technology, the front-end is no longer the traditional front-end. Various front-end frameworks (Vue, react, angular, etc.) have developed rapidly. With the rendering engine of nodejs server, the work that the front-end can complete is not limited to CSS, JS and other aspects. Many system business logic can be completed on the front-end.

At present, the cooperation mode of front-end and back-end is the separation of front-end and back-end, which can be decoupled effectively through the combined deployment of nginx + Tomcat (and nodejs middleware can also be added), and the separation of front-end and back-end lays an important foundation for the future architecture expansion, micro service and Componentization of the project, so this is an inevitable trend in the future, we need to adapt and make changes!!!

Early development methods

The early development mode is as follows:

Thinking and summary of front and back end docking

Exploration of separation of front and rear ends

jsonp

Maybe because I have accumulated rich front-end experience in the previous three years, I was mainly responsible for developing the interfaces of the official website, wechat, background and other related systems in the previous company. In the early stage, although our development method was also the separation of front-end and back-end, most of us used the method of cross domain interface invocation of jsonp to achieve the separation effect, and all the back-end interfaces were in the form of cross domain invocation of jsonp, Leaving aside the interfaces other than the authorized ones that need to be logged in, the front-end can call the server-side interface when developing, and then render the data to complete the interactive rendering effect of the page

Advantages of jsonp

Unlike Ajax requests implemented by XMLHttpRequest objects, they are limited by the same origin policy
The compatibility is better, and it can be compatible in the lower version of IE browser, which is different from CORS cross domain type
In fact, the principle of jsonp is very simple. Of course, it also involves the knowledge of the front end. To put it simply, it is the function execution of JS end

Normal back-end response data, for example:

{
 "code":"8200",
 "data":{
 "id":"100",
 "name":"Test"
 //more......
 }
}

Return format required by jsonp:

callback({
 "code":"8200",
 "data":{
 "id":"100",
 "name":"Test"
 //more......
 }
});

The front-end defines a callback function on the page. The callback function receives the data JSON data from the back-end response. After the back-end response, it executes the callback function to call the front-end business logic and render the page

nginx+ajax

This coordinated development method is also suitable for the front-end without introducing node and other one-stop development solutions. Pure HTML + CSS + JS connects with the back-end, binds business interfaces, and renders data

When we use jsonp for development, the front end needs to write the host + IP interface address on the page, There is a major drawback that the front-end needs some config files to configure the interface request address of our back-end. If the front-end engineers have a stronger sense of specification, they will be used in a configuration file. But if they do not have this sense, there will be hard coding in the code, which is not conducive to server migration, code update, interface change and other operations

In order to avoid the above problems, the reverse proxy function of nginx is used to proxy the back-end server. The front-end opens the nginx service locally during the development, which solves the cross domain problem of jsonp. At the same time, it also solves the problem that there is no need to write the IP + port address of the back-end service, which is conducive to the back-end integrating code during deployment and reducing unnecessary errors

node

With the popularity of nodejs, when the front end has been able to open the service writing interface locally, it is similar to the server opening Tomcat. In this case, the front-end framework Vue and react provide a complete set of technical solutions on this basis, which is a bit similar to the above mentioned opening nginx service architecture

The significance of doing so: the real liberation of the front and rear end, focusing on their respective areas of expertise

The technical framework is as follows:

Thinking and summary of front and back end docking

The front-end node service directly accesses the back-end Java restful API interface service. The API interface finally accesses the database to complete the data query, and finally returns to the node layer. The node renders the response data to the front-end

If there are problems such as session information synchronization, middleware, such as redis cache database, can be used to solve the problem of front-end node and back-end API information synchronization. Parameter transfer can complete the interface permission verification through JWT and other methods

Whether it is jsonp or Ajax + nginx, node as middleware can easily switch processing, and node as the middle layer, can also combine multiple back-end interfaces into a whole data set, and finally render the front-end in a synchronous way, which is also conducive to SEO optimization, which can not be achieved by the previous two ways

As for the separation of front and rear end, you can read the thinking and practice of separation of front and rear end in detail. This article lists the practical experience of separation of front and rear end in detail

Talking about interface

With the separation of front-end and back-end, back-end engineers don’t need to write pages or JS, they just need to provide an interface. However, for many back-end development engineers, in the process of actual development and docking with front-end, the problem is still very serious

Many back-end students say that I am only responsible for writing interfaces, and I don’t care about anything else. The consequence is that

1. The interface structure is disordered and disordered

2. The interface does not match the actual business scenario and is not available

3. Frequent communication with the front end, simple things complicated, front and back end are very angry

4. Things didn’t go well

Before writing interfaces, the back-end should first understand the business. Before fully understanding the business, coding is meaningless. As a back-end, it needs to exercise its ability to consider the overall situation of the whole system. Interfaces are not unrelated. We are writing the first interface, The business logic between other interfaces may take into account that this is particularly important when the back end team works together to develop different functions

When developing interfaces, I think we should pay attention to the following aspects:

Interface URL definition
Interface type and parameters
Global error code definition
Interface JSON format
Interface documentation

Interface URL definition

For back-end developers, the front-end of the interface can be used as a reference, Finally, the database resources are combined and queried. After a series of calculations in related business scenarios, the front-end JSON data is responded. The path definition of each layer of URL needs to be clear. This is the same as the back-end transaction management defined by AOP. The back-end service needs to meet certain naming specifications, which is convenient for unified management. Moreover, with this specification, the subsequent front-end and back-end docking will be much easier

In order to provide a consistent developer experience in many APIs and over time, all names used by the API should be:

This includes the names of interfaces, resources, collections, methods, and messages.

Since many developers are not native speakers of English, one of the goals of these naming conventions is to ensure that most developers can easily understand the API. It does this by encouraging a simple, consistent, and small vocabulary for naming methods and resources.

The name used in the API should be correct American English. For example, license (not license), color (not color).
You can simply use the commonly used short form or long word abbreviation. For example, APIs are superior to application programming interfaces.
Use intuitive and familiar terms as much as possible. For example, when describing the deletion (and destruction) of resources, deletion takes precedence over erasure.
Use the same name or term for the same concept, including the concept of sharing across APIs.
Avoid name overloading. Use different names for different concepts.
Carefully consider using names that may conflict with keywords in common programming languages. These names can be used, but additional reviews may be triggered during API reviews. Use them carefully and cautiously.
Interface type and parameters

As for the request types of interfaces, they are commonly used: get, post, put, delete and patch

Get (select): fetches one or more resources from the server. Post (create): create a new resource on the server.
Put (update): update the resource on the server (the client provides the changed complete resource).
Patch (update): update the resource on the server (the client provides changed attributes). Delete (delete): delete a resource from the server.
The back end can define different interface types according to different business scenarios

When defining interface parameters, we usually use several submission methods

Form submission,application/x-www-form-urlencoded

Thinking and summary of front and back end docking

Form submission is mainly for key value submission

The Java fragment is as follows:

@PostMapping("/queryAll")
public RestfulMessage queryAll(RuleCheckLogs ruleCheckLogs, @RequestParam(value = "current_page",defaultValue = "1")Integer current_page
 , @RequestParam(value = "page_size",defaultValue = "10")Integer page_size
 , @RequestParam(value = "tableName",required = false) String tableName){
 RestfulMessage restfulMessage=new RestfulMessage();
 try{
 assertArgumentNotEmpty( ruleCheckLogs.getProjectId (), "quality inspection scheme ID cannot be empty"); restfulMessage.setData (qc RuleCheckLogsService.queryRuleLogsByPage (ruleCheckLogs,tableName,current_ page,page_ size));
 }catch (Exception e){
 restfulMessage=wrapperException(e);
 }
 return restfulMessage;
}

File stream submission

JSON submission, application / JSON

Thinking and summary of front and back end docking

There are two main ways to submit JSON in spring MVC or spring boot, one is to receive @ requestbody annotation, the other is to receive httpentity < string > requestentity byte

Java code example:

@PostMapping("/mergeModelEntitys")
public RestfulMessage mergeModelEntitys(HttpEntity<String> requestEntity){
 RestfulMessage restfulMessage=new RestfulMessage();
 try{
 JsonObject paramsJson = paramJson(requestEntity);
 Assertjsonnotempty (paramsjson, "request parameter cannot be empty");
 //more...
 }catch (Exception e){
 restfulMessage=wrapperException(e);
 }
 return restfulMessage;
}

There are two main ways to submit JSON in spring MVC or spring boot, one is to receive @ requestbody annotation, the other is to receive httpentity < string > requestentity byte

Java code example:

@PostMapping("/mergeModelEntitys")
public RestfulMessage mergeModelEntitys(HttpEntity<String> requestEntity){
 RestfulMessage restfulMessage=new RestfulMessage();
 try{
 JsonObject paramsJson = paramJson(requestEntity);
 Assertjsonnotempty (paramsjson, "request parameter cannot be empty");
 //more...
 }catch (Exception e){
 restfulMessage=wrapperException(e);
 }
 return restfulMessage;
}

Global error code definition

The definition of error code is the same as the HTTP request status code. The docking user can quickly understand the error information returned by the interface through the system defined error code, which is convenient for troubleshooting

{
 "code": "8200",
 "message": "Success",
 "data": {
 "total_page": 1,
 "current_page": 1,
 "page_size": 10,
 "count": 5,
 "data": [
 {
 "id": "a29ab07f1d374c22a72e884d4e822b29",
 //......
 }//....
 ]
 }
}

Interface JSON format

The back-end response to JSON to the front-end needs to pay attention to the following points:

1. The JSON format needs to be fixed

For example, the following figure

Thinking and summary of front and back end docking

As shown in the figure above, the horizontal direction is time, and the vertical direction is value

Our JSON structure should be as follows:

[
 {
 "date":"2018-01",
 "value":100
 },
 {
 "date":"2018-02",
 "value":200
 }
 //more...
]

In our work, we often encounter such data formats

[
 "2018-01":{
     value:100
 },
 "2018-02":{
     value:200
 }
 //more...
]

The fixed JSON format mentioned here is mainly aimed at this situation. The interface format from the back end to the front end must be fixed, and all dynamic data values need corresponding keys

2. All returned interface data should be directly available, the simpler the better

The interface data provided by the back-end to the front-end is finally handed over to the front-end. It only needs to let the front-end render the data. The simpler the data, the better. The front-end does not have to deal with too much business logic. All complex business logic that can be merged and avoided needs to be dealt with by the back-end

Interface documentation

Interface document writing is an important basis for front-end and back-end docking. The back-end specifies the interface document, and the front-end docks according to the interface document

At present, the document situation is mainly divided into several types

1. Rely on the swagger framework to automatically generate interface documents (swagger can only generate detailed parameters based on key value, but can’t specify the specific request content for JSON format)

2. Manual preparation of documentation, recommended markdown preparation

Interface docking

Everything is ready except Dongfeng. Although we have prepared everything we should prepare above, the interface definition is perfect, and the interface documents have explained it, there may still be problems during docking. At this time, I think we need to pay attention to the details

1. JUnit unit test is required for back-end interface

At present, spring integrates JUnit framework to facilitate unit testing, including business bean method testing and API mock testing

@RunWith(SpringRunner.class)
@SpringBootTest
public class QcWebApplicationTests {
    @Autowired
    private WebApplicationContext context;
    private MockMvc mvc;
    @Autowired
    QcFieldService qcFieldService;
    @Before
    public void setUp() throws Exception {
 //Initialize the mock object
        mvc = MockMvcBuilders.webAppContextSetup(context).build();
    }
    @Test
    public void queryByDsId(){
        try {
 //For mock interface controller layer testing
            mvc.perform(MockMvcRequestBuilders.post("/qc/entity/queryByDsId")
 .contentType(MediaType.APPLICATION_JSON_UTF8)
 .param("dsId", "7d4c101498c742368ef7232f492b95bc")
 .accept(MediaType.APPLICATION_JSON))
 .andExpect(MockMvcResultMatchers.status().isOk())
 .andDo(MockMvcResultHandlers.print());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
 @Test
 public void testUpdateField(){
        QcField qcField=new QcField();
        qcField.setId("513ee55f5dc2498cb69b14b558bc73e6");
        qcField.setShortName (the "password");
 //Business bean service method testing
        qcFieldService.updateBatchFields(Lists.newArrayList(qcField));
    }

2. Use tools to test, recommend postman

As an interface debugging artifact, everyone must have known the name of postman

As a back end, we need to learn to check the functions of the review elements recommended by chrome. Please refer to the introduction of chrome development tools

Chrome provides a URL function that can copy the current interface, and finally generate curl command line

Thinking and summary of front and back end docking

Finally, curl command can be generated by copy as curl (bash) function

curl 'http://demo.com/qc/ds/getAll' -H 'Origin: http://demo.com' -H 'Accept-Encoding: gzip, deflate' -H 'Accept-Language: zh-CN,zh;q=0.9' -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36' -H 'Content-Type: application/x-www-form-urlencoded' -H 'Accept: application/json, text/plain, */*' -H 'Referer: http://demo.com/index.html' -H 'Connection: keep-alive' --data 'current_page=1&page_size=6&' --compressed

The above commands can be executed directly in Linux and other terminals

Curl command is a file transfer tool that uses URL rules to work under the command line. It supports file upload and download, so it is a comprehensive transmission tool, but traditionally, curl is called download tool. As a powerful tool, curl supports many protocols including HTTP, HTTPS, FTP, etc., and also supports post, cookies, authentication, downloading partial files from the specified offset, user agent string, speed limit, file size, progress bar, etc. Curl can give a hand to the automation of web page processing and data retrieval.

Postman provides the import curl command line

Thinking and summary of front and back end docking