Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Thoughts on the practice of front and rear separation

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/03 Report--

Front-end separation is nothing new, and there are practices of front-end separation everywhere. However, some historical projects will inevitably encounter a variety of problems when they change from integrated Web design to front-end and back-end separate architecture. Due to endless problems, some teams may even question that the integration is good, why should the front and rear be separated?

In the final analysis, it is not that the front and back separation is not good, but it may not be suitable, or …... The design thinking has not changed yet.

Integrated Web architecture schematic

Schematic of front and rear separated Web architecture

Why are the front and rear ends separated?

The more realistic question than why the front and rear ends are separated is when the front and rear ends are needed, that is, the application scenarios where the front and rear ends are separated.

Speaking of this, I think that around 2011, the company expanded the Java team based on the .NET development team. although the two teams are working on different products, there is still a lot of repetitive development, such as writing organizational pages in ASP.NET WebPage and writing it again in JSP. In this case, the team began to think about such a solution: if the front-end implementation has nothing to do with the back-end technology, then the part of the page presentation can be shared, and different back-end technologies only need to implement the back-end business logic.

The fundamental problem to be solved by the solution is to separate the data from the page. The technology to deal with this demand is ready-made, the front end uses the static web page related technology, HTML + CSS + JavaScript, through the AJAX technology to call the business interface provided by the back end. The front and back end negotiates that the interface is provided through HTTP, and the POST predicate is used uniformly. The interface data structure is implemented using XML, the front-end jQuery parses XML conveniently, and the back-end has more processing tools for XML. Later, due to the rise of back-end JSON libraries (such as Newtonsoft JSON.NET, jackson, Gson, etc.) and easier front-end processing of JSON (JSON.parse () and JSON.stringify ()), the data structure was replaced with an JSON implementation.

This architecture is essentially SOA (service-oriented architecture). When the back end does not provide pages, but simply provides data and business interaction capabilities through Web API, the Web front end becomes a pure client role, which belongs to the same role as WinForm and mobile terminal applications, which can be combined together, collectively called the front end. The previous integrated architecture required customized pages to implement Web applications, while defining a set of WebService/WSDL to provide services to WinForm and mobile terminals. After conversion to the new architecture, you can uniformly use the Web API form to provide services for all types of front ends. As for the RPC encapsulation of this Web API by some types of front end, that is another matter.

Through such an architectural transformation, the front and rear ends are actually separated. Leaving aside other types of front-ends, only Web front-ends and back-ends are discussed here. Because of the separation, the Web front end does not need to know what technology is used in the back end at all, just what kind of interface the back end provides can be used to do what things, such as C#/ASP.NET, Java/JEE, database. These technologies can not be understood at all. On the other hand, the back-end .NET team and Java team are also divorced from the aesthetic thinking that has nothing to do with logic. they do not need to face the fine interface design constraints of artists, nor do they need to consider the layout of the page while thinking about the logic implementation. They just need to deal with the logic and data that they are good at.

After the separation of the front and rear ends, the developers at both ends are much easier, and the development efficiency is improved as a result of greater technical and business focus. The benefits of separation are gradually emerging:

1. Separation of duties before and after

The front end tends to present, focusing on issues related to user experience, while the back end focuses on business logic, data processing and persistence. In the case of a clear design, the back end is only responsible for the business processing algorithm with data as the center, and provides the API interface for the front end as agreed, while the front end uses these interfaces to be responsible for the user experience.

two。 Front and back technical separation

The front end does not need to understand the back-end technology, nor does it care about what technology the back-end uses to implement it. It only needs to know HTML/CSS/JavaScript to start. The back-end only needs to care about the back-end development technology, except to save the trouble of learning the front-end technology, even the study of the Web framework only needs to pay attention to Web API, but not to the MVC technology based on the page view (not that the data structure presentation of the interface part of the MVC,Web API is also View), and does not need to consider the particularly complex data organization and presentation.

3. The separation brings about the decoupling of user experience and business processing.

The front end can be quickly modified according to the experience needs of users in different periods, and the back end has no pressure on it. By the same token, the front end can be unaware of the business logic upgrade and data persistence scheme change carried out by the back end as long as the interface is not affected. Of course, if the interface changes caused by a change in requirements, the front and back ends need to sit together to synchronize information.

4. The front and rear separation can be reduced to the design of both ends respectively.

The backend only provides API services, regardless of the problem of page rendering. The API that implements the SOA architecture can serve all kinds of front ends, not just the Web front end, and can achieve a set of services that can be used by all ends. At the same time, for the front end, the front part that does not depend on the back-end technology can be deployed independently, or it can be embedded in various "shells" (such as Electron, Codorva, etc.) in the Hybrid architecture to quickly achieve multi-terminals.

Front and back separation architecture

Any technical solution is not a silver bullet, and the separation brings not only benefits but also contradictions. At the beginning of our practice, because the strength of the front-end team is relatively weak, and according to the usual practice, almost all business processes are designed and defined by the back-end (the original technical backbone). In the front-end processing, we often find that the interface definition does not conform to the user operation flow, too many AJAX asynchronous requests and so on. After all, back-end thinking is still different from front-end thinking-front-end thinking tends to user experience, while back-end thinking is more inclined to the technical implementation of the business.

In addition, the security requirements of front and back separation are also slightly different. Since pre-and post-separation is essentially a SOA architecture, authorization also needs to be thought in the same way as SOA architecture. Although the Cookie/Session approach is available, it is not particularly appropriate. Relatively speaking, Token-based authentication is more suitable. Adopting Token-based authentication means that the authentication part of the back end needs to be rewritten. Of course, the back end does not want to rewrite, so it will kick the ball to the front end to find a way to achieve Cookie/Session-based authentication. So the front end began to complain (tragedy).

Who will take the lead?

In the final analysis, the emergence of these contradictions lies in that the design is not clear enough. There is no doubt that in the development process, the leader should be the architect or designer. However, in the actual scenario, architects or designers are often also developers, so their main technical stack will greatly affect the primary and secondary role of the front and rear end in the whole project. Where the backbone is located, the convenience of development will tilt to which end. This is a bad phenomenon, but we have to face this situation, and I believe many small teams are facing similar problems.

If there is no good process specification, the front end is usually exposed to more roles than the back end (most application projects / products, not in all cases).

Front-end developers are directly influenced by the project / product manager or customer: there should be a button in this place, and that operation should be done this way. The front end also has to be docked with artists-- this kind of design is not easy to implement, can it be changed to that? The customer requires this to be done, but the design cannot be done; the front end has to be docked with the back end, and for some applications, even multiple backends

In other words, the front end can be the center of project communication, so it is more appropriate to play a leading role than the back end.

Interface design

The interface is divided into two parts: back-end service implementation and front-end invocation, the technology is mature, it is not difficult, interface design is the difficulty. As mentioned earlier, there will be some contradictions between the front and rear ends. From the front-end point of view, focus on the user experience, including the flow direction of users in business operations and related processing; from the back-end point of view, focus on the integrity, effectiveness and security of data. The contradiction lies in the different concerns, information asymmetry and selfishness of both sides. The starting point to solve these contradictions is interface design.

When designing an interface, its granularity often represents the amount of work done at the front and back end (non-absolute, which is related to the overall architecture). If the granularity of the interface is too small, the front end will have a lot of things to deal with, especially for all kinds of asynchronous processing; if the granularity is too large, there will be high coupling and reduced flexibility and expansibility. Of course, in this case, the back-end work will not be easy. Things at the business level involve specific products, which are not discussed here. Here we mainly discuss a little bit of technical stuff.

Formally, Web API can be defined as REST or RPC, as long as the front and back end is negotiated and determined. More importantly, it is best to have a relatively fixed definition of input parameters and output results from the beginning, which often depends on the front-end architecture or the UI framework adopted.

The data forms of common request parameters are as follows:

Key-value pairs, PayloadXML/JSON/..., for methods such as QueryString or POST in URL is usually used in Payload for methods such as POST, or you can use multipart to pass ROUTE, which is obtained by back-end route parsing URL, which is commonly used in RESTful.

On the other hand, the data forms of the server response are varied, and usually a complete response needs to include at least three parts: status code, message and data.

Status codes, HTTP status codes, or specific status attribute messages in response data, usually placed in the response content, as part of the data, depending on the interface protocol, may be in various formats, the most popular at present is JSON

We used the JSON form in practice and initially defined such a form.

{"code": "number", "message": "string", "data": "any"}

Code is mainly used to instruct the front end to perform some special operations. For example, 0 means the API call was successful, while non-0 means the call failed, where 1 means login is required and 2 means no authorization is obtained. For this definition, after the front end gets the response, you can do some general processing at the application framework layer. For example, when the code is 1, the pop-up login window asks the user to log in on the current page, and when the code is 2, a message will pop up with a link to guide the user to obtain authorization.

See: encapsulated Api calls for front-and-back separation models

There was no problem doing this at first until the front-end framework switched to jQuery EasyUI. Many UI libraries such as EasyUI support configuring data URL for components, which automatically fetches data through AJAX, but requires a data structure. If you still use the previously designed response structure, you need to define a data filter (filter) for the component to process the response results, which is a lot of work to write filter and declare filter for the component. 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 structure required by UI, but in case of error, it responds to a data structure of the type that is the original structure:

{"error": {"identity": "special identity string", "code": "number", "message": "string", "data": "any"}}

For the new response data structure, the front-end framework only needs to determine whether the error attribute exists, and if so, check whether its identity attribute is a specified special value (such as a particular GUID), and then use its code and message properties to handle the error. This misjudgment process is a little more complicated, but it can be handled uniformly by the front-end application framework.

If you use a RESTful-style interface, some status codes can be replaced by HTTP status codes. For example, 401 indicates that you need to log in, 403 indicates that you are not authorized, and 500 indicates that an error occurred during the program processing. Of course, although HTTP status codes are better suited to the RESTful style, non-RESTful styles can also use HTTP status codes instead of error.code.

User authentication

There are many authentication schemes, such as Cookie/Session is still feasible in some environments, can also use based on Token and OAuth or JWT, or even their own implementation of Token-based authentication.

Authentication Scheme based on Cookie/Session

It is not impossible to adopt the traditional Cookie/Session authentication scheme, but there are some limitations. If the front-end part and the back-end part are of the same origin, for example, the page is published on http://domain.name/ and the Web API is published on http://domain.name/api/, in this case, the Cookie/Session solution adopted in the original integrated Web solution can be migrated directly without pressure. But if the previous release is different from the API release, this approach is complicated.

Then, in the general development mode of separation of front and rear ends, whether in the development phase or the release phase, the possibility of different sources accounts for a large proportion, so authentication schemes usually use schemes that have nothing to do with Cookie.

Authentication Scheme based on OAuth

At present, the open interfaces of major websites are all SOA architectures. if we regard these open interfaces as the provider (server), and the applications using these open interfaces as clients, then we can produce such a relationship corresponding to the separation of front and back:

Front-end ⇌ client ⇣ OAuth-based authentication) ⇡ backend ⇌ server

Therefore, the OAuth scheme, which is widely used in open interfaces, is feasible for front and rear separation, but it is not so easy to implement. Especially in terms of security, because the front end is completely exposed, compared with the environment usually implemented by OAuth (back-end ⇌ server), it should be noted that the first authentication is not the use of registered AppID and AppToken, but the use of user name and password.

Authentication Scheme based on Token/JWT

Although this scheme is put at the end, it is the most suitable one for front-end and back-end separation at present. The authentication scheme based on Token has been discussed for a long time, and JWT is relatively mature and recognized by most people. The JWT implementation of various technology stacks can be found from jwt.io, and it is also convenient to apply.

Having said that, there is still a big difference in processing between the JWT scheme and the previously used Cookie/Session, which requires a certain learning cost. Some people worry that JWT has too much data. This is indeed a problem, but the hardware is not expensive, 4G also began to enter the unlimited traffic stage, general applications do not have to pay too much attention to this problem.

Front and back separation test

After the separation, the front-end testing will be based on user experience testing and integration testing, while the back-end will mainly be unit testing and Web API interface testing. Compared with the integrated Web application, there is one more layer of interface testing, which can be fully automated. Once the test development is completed, the business processing and data errors can be controlled to a great extent. As a result, the workload of integration testing is relatively simple and much easier.

The front-end testing work is relatively small, and the front-end part after the front-end separation undertakes the original integration testing work. However, under the assumption that the Web API is correct, the workload of integration testing can be greatly reduced, and the use case can only focus on the front-end experiential issues, such as whether the presentation is correct, whether the jump is correct, whether the user's steps meet the requirements, and whether the prompt information is accurate, and so on.

For the validation of user input, this part of the work can even be completely left to Web API to handle when the project time is tight. Whether the front and rear ends are separate or not, there is a consensus in Web development: never trust the front end! Since the back-end must ensure the security and validity of the data, omitting this step from the front-end will not pose any substantial threat to the back-end. At best, it will only cause a poor user experience. However, if both the front and back end have to do data validation, it must be done strictly according to the document, otherwise it is easy to cause inconsistent data verification (this is not a problem of separation, the same problem exists in the integrated architecture).

Summary

In general, the benefits of front and back separation are obvious. But the concrete implementation needs a new way of thinking, not based on the original integrated Web development way to think. The open way of separation of front and rear frees developers from the complex technology portfolio, and everyone can focus more on the areas they are good at, but at the same time, it also puts forward higher requirements for the communication between the front and back end teams. The front and back end teams must design a relatively stable Web API interface together (in fact, this part of the work is indispensable regardless of whether the front and rear ends are separated or not. It's just that the separate architecture requires higher requirements, and more clearly requires that the interface not only exist in human memory, but also be documented and persisted.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report