Front-end separation practice

Source: Internet
Author: User
Tags data structures oauth what interface

Original Author: border town
Original address: https://segmentfault.com/a/1190000012747428

The separation of front and back is not new, and there is a practice of separating back and forth. However, some historical projects are inevitably confronted with a variety of problems when moving from an integrated Web design to a front-end separation architecture. Because of the endless problems, even the team questioned, integration good, why the front and back separation.

In the final analysis, it is not good or bad separation, just may not fit, or say ... The design mindset has not yet turned around ...




One-piece WEB architecture schematic


Pre-and post-detached WEB architecture schematic

Why do you want to detach the front and back?

A more realistic question than why a back-and-forth separation is needed is when a front-end separation is required, i.e. the front-end separation of the application scenario.

Speaking of this problem, I think about 2011 years, the company in the. NET development team based on the expansion of the Java team, two teams are doing different products, but there are still a lot of repetitive development, such as the use of ASP. Webpage to write the organization-related pages, using JSP I'm going to write it again. In this case, the team began to think about the scenario: if the front-end implementation is not related to back-end technology, then the portion of the page rendering can be shared, and different backend technologies simply need to implement the backend business logic.

The problem with the solution is to separate the data from the page. The technology to address this requirement is readily available, with static web-related technologies at the front end, HTML + CSS + JavaScript, and the use of AJAX technology to invoke the business interface provided by the backend. The front and back ends negotiate the interface way provided via HTTP, using the POST verb uniformly. Interface data structure using XML implementation, the front-end jQuery parsing XML is very convenient, the back end of the XML processing tools more ... Later, due to the rise of the back-end JSON libraries (such as Newtonsoft Json.NET, Jackson, Gson, etc.), the front-end processing of JSON was easier (Json.parse () and Json.stringify ()), and the data structure was replaced with a JSON implementation.

This architecture is essentially SOA (service-oriented architecture). When the backend does not provide a page, but purely through the web API to provide data and business interaction capabilities, the Web front end becomes a purely client role, and WinForm, mobile terminal applications belong to the same role, can be combined together, collectively referred to as the front-end. The previous integration architecture required customized pages for WEB applications, while defining a set of webservice/wsdl to service WinForm and mobile terminals. After you convert to a new schema, you can use the Web API as a unified service for all types of front ends. As for some types of front-end RPC encapsulation of this Web API, that is another matter.

With such an architectural transformation, the front and back end is actually separated from each other. Aside from the other types of front end, this is just the Web front end and back end. Because of the separation, the Web front-end in the development of the time does not need to know what the backend is to use what technology, only need the backend to provide what interface can be used to do what things good, what c#/asp.net, Java/jee, Database ... These technologies can never be understood. The back end of the. NET team and the Java team also divorced from the logic-independent aesthetic thinking, do not have to face the art of fine-grained interface design constraints, and do not need to think about the logical implementation of the page, but also to consider how the layout of the problem, only need to deal with their own good logic and data.

After the separation between the front and back ends, developers at both ends have a lot of ease, as technology and business are more focused and development efficiencies are increased. The benefits of separation are gradually reflected: 1. Separation of duties and responsibilities

The front-end tends to be presented, focusing on the user experience-related issues, and back-end dumping in business logic, data processing and persistence. In the case of clear design, the backend only has to be responsible for the data-centric business processing algorithms and provide API interfaces to the front-end as agreed, while the front-end uses these interfaces to be responsible for the user experience. 2. Technical separation before and after

The front end can not understand the back-end technology, but also do not care about what the backend specific technology to achieve, only need to html/css/javascript can start; the backend only needs to care about the backend development technology, in addition to eliminating the problem of learning front-end technology, even the web framework of learning research only need to focus on the Web API Rather than focus on the page view-based MVC technology (not to say that the data structure of the interface part of the Mvc,web API is also view), regardless of particularly complex data organization and presentation. 3. Front-to-back separation brings user experience and business understanding decoupling

The front end can be based on the user's experience in different times of the rapid revision, the back end of this no pressure. Similarly, the back-end business logic upgrade, data persistence scheme changes, as long as the interface is not affected, the front-end can be without knowledge. Of course, if the demand changes caused by the interface changes, the front and back end need to sit together to synchronize information. 4. Separation between front and rear, can be divided into the design of the two ends

The backend only provides API services, regardless of the issue of page rendering. The API to implement SOA architecture can serve a variety of front end, not just the Web front end, can do a set of services, each end of the use, and for the front end, independent of the front end of the backend technology can be deployed independently, or in the Hybrid architecture, embedded in various "shells" (such as Electron, Codorva, etc.), quickly realize multi-terminal. pre-and post-separation architecture

Any technical solution is not a silver bullet, the separation of the front and back not only brings benefits, but also brings contradictions. At the beginning of our practice, due to the relatively weak front-end team, and by convention, all business processing is almost by the backend (the original technical backbone) to design and define, front-end processing often found that the interface definition does not conform to the user operation process, AJAX asynchronous request too many problems. After all, back-end thinking and front-end thinking is still different-the front-end thinking tends to the user experience, and the backend thinking is more inclined to the technical implementation of the business.

In addition, the requirements for safety in front and back separation are slightly different. Since pre-and post-separation is essentially an SOA architecture, it is also necessary to think in terms of the SOA architecture for authorization. Cookie/session's approach, though available, is not particularly appropriate, and Token-based authentication is more appropriate. Using Token-based authentication means that the back-end authentication section needs to be rewritten ... The back end of course does not want to rewrite, so the ball will be kicked to the front end to find ways to achieve the front-end based on cookie/session certification ... So the front end began to complain (tragedy) ... who's going to dominate

The emergence of these contradictions in the final analysis of the design is not clear. There is no doubt that in the development process, the leader should be an architect or designer. However, in real-world scenarios, architects or designers are often developers, so their main technology stack will greatly affect the primary and secondary roles of the front and back end throughout the project. The backbone on which side, the development of the convenience of the end of the tilt. This is a bad phenomenon, but we have to face the situation, I believe that many of the less large teams also face similar problems.

If there is no good process specification, the role of front-end contact is usually more than the backend (most of the application projects/products,
Not in all cases). Front-end developers are directly affected by the project/Product Manager or Customer: This place should have a button, that should be done ... And the front end to the art of docking-the design is not good to achieve, whether it can be changed to that. Customer requirements must be done, but this design does not work, the front end is also connected to the backend, for some applications, even multiple back-end.

In other words, the front end can be the center of Project Communication, so it is more appropriate to assume the leading role than the backend. Interface Design

Interface sub-terminal service implementation and front-end call two parts, technology is mature technology, not difficult, interface design is difficult. There are some contradictions in front and back. From the front-end point of view, the focus is on the user experience, including the user in the business operation of the flow direction and related processing, and from the back-end point of view, the focus is the data integrity, effectiveness, security. The contradiction is that the two sides have different concerns, asymmetric information and selfish motives. The focus of solving these contradictions is interface design.

interface design, the size of its granularity often represents the size of the front and back workload (not absolute, which is related to the overall architecture). Interface granularity is too small, the front end to deal with more things, especially for a variety of asynchronous processing may be overwhelmed, the granularity is too large, there will be high coupling, reduce flexibility and scalability, of course, in this case the back end of the work is not easy. Business-level things involve specific products, and there's not much to discuss here. Here we discuss a little bit of technical stuff.

Formally, the Web API can be defined as REST, or RPC, as long as the front-end negotiation is OK. More importantly, in the input parameters and output results, it is better to start with a relatively fixed definition, which often depends on the front-end architecture or adopted UI framework.

The data forms of the common request parameters are as follows: key-value pairs, Payload xml/json/for methods such as QueryString or post in URLs, typically used for Payload of methods such as post, or multipart delivery ROUT E, obtained by the backend routing resolution URL, commonly used in RESTful

The server response data form a variety of different, usually a complete response needs to contain at least the status code, messages, data three parts of the content, where the status code, HTTP status Code or response data in a particular state attribute message, usually in the response content, as part of the data, Depending on the interface protocol, there may be various formats, and the most popular is JSON

We used the JSON form in practice, initially defining such a form

{
    "code": "Number",
    "message": "string",
    "data": "Any"
}

Code is mainly used to guide the front-end to do some special operations, such as 0 to indicate that the API call succeeds, not 0 to indicate that the call failed, where 1 means login required, 2 means no authorization ... For this definition, the front end of the response, you can do some general processing in the application framework layer, such as when code is 1, the popup login window to the user to log on the current page, and when code is 2, then pop up a message prompt and a link to guide the user to obtain authorization.

It didn't matter at first, until the front-end frame swapped with the JQuery Easyui. Many UI libraries, such as Easyui, support the configuration of the data URL for the component, which automatically obtains data through AJAX, but has requirements for a data structure. If you still adopt the previously designed response structure, you will need to define a data filter for the component (filter) to handle the response results, so that writing the filter and declaring the filter for the component is not a small effort. In order to reduce this part of the workload we decided to change the interface.

The new interface is a mutable structure that normally returns the data structures required by the UI, and in the case of an error responds to a data structure of the original type:

{"
    error": {
        "identity": "Special Identity string",
        "code": "Number",
        "message": "string",
        "data ":" Any "
    }
}

For a new response data structure, the front-end framework only needs to determine if there is an error property, and if so, check whether its identity property is a specified special value (such as a specific GUID), and then use its code and message properties to handle the error. This error-judging process is somewhat more complex, but can be handled uniformly by the front-end application framework.

If you use a RESTful interface, some status codes can be replaced with HTTP status codes, such as 401 for login, 403 for no authorization, and 500 for errors during program processing. Of course, while the HTTP status code is more of a restful style, the non-restful style can also use HTTP status codes instead of Error.code. user authentication

There are many authentication schemes, such as cookie/session, which are still viable in some environments, and can be used based on token and OAuth or JWT, or even self-token-based authentication. Cookie/session-based authentication scheme

Using traditional Cookie/session certification schemes is not an option, but there are some limitations. If the front-end and back-end parts of the same origin, such as the page is published in http://domain.name/, and the Web API is published in http://domain.name/api/, in this case, the original one-piece Web schema used by the Cookie/session The scheme can be migrated directly, without pressure. But if the previous release and API publish different sources, this approach is complex to handle.

Then the general front-end separation of the development method, whether it is the development phase or release phase, the likelihood of non-homologous accounted for a large proportion, so the certification scheme will usually use a Cookie-independent scheme. OAuth-based authentication scheme

At present, the open interface of the major web sites are SOA architectures, if these open interfaces as a service side (server), and the use of these open interface applications as a client, then you can create such a relationship with the pre-and post-separation corresponding:

Front-end ⇌ client
     ⇣
   OAuth-based authentication
     ⇡ 
backend ⇌ Server

Therefore, it is feasible to use OAuth schemes widely used in open interfaces for pre-and post-separation, but it is not so easy to implement in detail. Especially in terms of security, because the front end is completely exposed, compared to the environment typically implemented by OAuth (backend ⇌ server), it is important to note that the first authentication is not the use of registered AppID and Apptoken, but rather the use of usernames and passwords. TOKEN/JWT-based authentication scheme

Although this scenario is final, the solution is the most appropriate solution for the current and front-end separation. Token-based authentication schemes have been discussed for a long while, and JWT is a relatively mature and most recognized one. From the Jwt.io can find a variety of technology stack of JWT implementation, the application is more convenient.

That said, the JWT scheme and the previously used cookie/session in the processing still have a big difference, need a certain learning cost. Some people worry that the data volume of JWT is too large. This is really a problem, but the hardware is not expensive, 4G also began to enter the unlimited traffic phase, the general application does not care too much about this problem. pre-and post-separation tests

After the separation, front-end testing will be based on user experience testing and integration testing, the latter is mainly for unit testing and Web API interface testing. Compared with the integration of WEB applications, a layer of interface testing, this layer of testing can be fully automated, once the test development, to a large extent to control business processing and data errors. As a result, the workload of integration testing is relatively simple and much easier.

The work of the front-end testing is relatively less, and the front-end part after the separation has assumed the original integration test work. However, in the assumption that the Web API is correct for integration testing, the workload can be reduced a lot of, use cases can only focus on the front-end experience problems, such as whether the rendering is correct, the correct jump, the user's steps to meet the requirements and whether the prompt information is accurate and so on.

For user input validation This part of the work can even be completely thrown into the Web API when the project time is tight. Regardless of whether or not the front-end separation, there is a consensus in WEB development: Never trust the frontend. Since the backend has to ensure the security and effectiveness of the data, then the front-end omission of this step does not pose any substantial threat to the backend, at best only the user experience is nearly. However, if the front and back end are to do data validation, it must be strictly in accordance with the documentation, otherwise it is easy to have the front and back end data validation inconsistencies (this is not a problem of separation, the integration of the same architecture). Summary

Overall, the benefits of separation are obvious. But the implementation needs a new way of thinking, not based on the original integrated WEB development approach to think. The open-and-closed approach frees developers from complex technology portfolios, where they can focus more on their areas of expertise, but at the same time put a higher demand on communication between the front and back teams, and the front and back teams must design a relatively stable Web API together. Interface (this part of the work in fact, regardless of whether the front-end separation is indispensable, but the pre-and post-separation of the architecture of this requirement is higher, more specifically requires that the interface is not only in human memory, but also documented, persistent).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.