Talking about the basic principles of front-end and back-end interaction

Audience of this article:

Front-end/back-end development engineer; Web application designer; Project manager; Product manager, etc.

Why do you want to know?

Understanding the fundamentals of front-end and back-end interaction is very important for people working in roles related to web development. This includes front-end developers, back-end developers, full-stack developers, web application designers, project managers, and product managers, among others. Whether you work in development, design, or management, understanding the fundamentals of front-end and back-end interactions will help you better understand and drive web application development and delivery.

Its basic principles generally include the following aspects, and this article will also elaborate on their respective functions and significance from these aspects

  • HTTP protocol

  • AJAX technology

  • Data Format and Transmission

  • Front-end and back-end communication methods

  • Interface Design and Specification

  • Cross-Origin Resource Sharing (CORS) and Security6ac9fb71b8affddbd35897fb137d7fb9.png

HTTP protocol

In front-end and back-end interaction, HTTP (Hypertext Transfer Protocol) protocol is one of the most commonly used protocols. HTTP is an application layer protocol used to transfer data between web applications. It defines the rules and conventions for communication between clients and servers.

The following are some key concepts and points of the HTTP protocol:

  1. Requests and Responses: HTTP communication takes place through requests and responses. The client sends an HTTP request to the server, and the server processes the request and returns an HTTP response to the client.

  2. Method: HTTP defines several request methods, common ones are GET, POST, PUT, DELETE, etc. Different methods are used to perform different operations such as fetching resources, submitting data, updating resources, and deleting resources.

  3. URL: URL (Uniform Resource Locator) is used to identify the location of the resource to be accessed. It consists of protocol type, server address, path and optional query parameters.

  4. Request header: An HTTP request includes a request header, which is used to pass metadata about the request, such as the requested method, requested resource, requested content type, etc.

  5. Request body: Some requests, such as POST requests, can contain a request body. The request body is used to pass data to the server, such as form data, JSON data, etc.

  6. Response Status Code: An HTTP response includes a status code that indicates the result of processing the request. Common status codes include 200 for success, 404 for resource not found, and 500 for internal server errors.

  7. Response header: The HTTP response also includes a response header, which is used to pass metadata about the response, such as the content type of the response, the length of the response, and so on.

  8. Response body: The response body is the actual data content returned by the server to the client, which can be different types of data such as HTML, JSON, and pictures.

  9. Cookie and Session: The HTTP protocol supports the use of Cookie and Session to maintain state. The server can store some client state information by setting a cookie in the response, and the client saves the cookie and sends it to the server in subsequent requests.

880f641a03e642e1315fac6971ade815.pngThe HTTP protocol is a stateless protocol, each request and response are independent of each other, and the server does not retain state information about the client. In order to solve this problem, mechanisms such as Cookie, Session, and Token are often used to implement user authentication and session management.

By following the HTTP protocol, the front-end and back-end can perform operations such as data interaction, resource acquisition, and state management to realize complex front-end and back-end interaction logic.

AJAX technology

AJAX (Asynchronous JavaScript and XML) is a technology for asynchronous data interaction in web applications. It updates part of the page content by exchanging data with the server through the background without refreshing the entire page.

Here are the key takeaways from AJAX techniques:

  1. Asynchronous communication: AJAX uses an asynchronous communication mechanism, that is, in the process of sending and receiving data in the background, it will not block the loading of the user interface or the entire page. This allows the page to remain responsive while allowing data to be processed in the background.

  2. XMLHttpRequest object: AJAX uses the XMLHttpRequest object to achieve data interaction with the server. It allows sending requests to the server through JavaScript code, and receiving and processing the data returned by the server.

  3. Data format: AJAX is not limited to data exchange using XML format, although XML was commonly used in early AJAX applications. Now, the common data formats are JSON (JavaScript Object Notation) and XML, and the appropriate data format should be selected according to the requirements of the application.

  4. Event-driven programming: AJAX is based on an event-driven programming model. By listening to various events of the XMLHttpRequest object (such as request completion, state change, etc.), corresponding operations can be performed at an appropriate time, such as updating page content, processing returned data, and so on.

  5. Cross-domain request: Due to the browser's same-origin policy restrictions, AJAX usually cannot request data across domains. To get around this, techniques like Cross-Origin Resource Sharing (CORS) or JSONP can be used to allow cross-origin requests.

  6. Security considerations: Since AJAX requests are made in the background, security considerations need to be taken into account. Especially when handling user input or sending sensitive data, suitable validation and protection measures are required to prevent security breaches.

ac757d92e96d9770974750f27d0619cb.pngThe application of AJAX technology can improve user experience, improve the performance and efficiency of Web applications. By partially updating the content of the page, the use of network bandwidth can be reduced, the loading speed of the page can be improved, and the function of updating data in real time can be realized. AJAX is often used to implement scenarios such as form submission without refresh, real-time search, and dynamic loading of content.

Modern front-end frameworks and libraries such as React, Angular, and Vue also provide more advanced tools and technologies to simplify and optimize AJAX operations, enabling front-end developers to more easily handle asynchronous data interactions.

Data Format and Transmission

In the front-end and back-end interactions, the data format and transmission method are very important aspects, which determine the structure of the data and how to transfer it between different systems.

Data Format:

  1. JSON (JavaScript Object Notation): JSON is a lightweight data exchange format widely used in front-end and back-end data interaction. Based on JavaScript's object literal notation, it's easy to read and write, as well as easy to parse and generate. JSON supports the representation of primitive data types (strings, numbers, booleans, null), objects, and arrays.02931f66557c133ca671a6b7f45ad9fc.png

  2. XML (Extensible Markup Language): XML is a general-purpose markup language used to represent structured data. It can describe complex data structures and hierarchical relationships, and has good scalability. The strict format of XML requires the use of tags to define the structure and semantics of the data.988451b5a9429effa736116e4779f00b.png

transfer method:

  1. HTTP (Hypertext Transfer Protocol): HTTP is the most commonly used transfer protocol for transferring data between web applications. Through the HTTP protocol, you can use methods such as GET and POST to send requests and receive responses.2482c4f7c495ef26318c9b44874ea023.png

  2. WebSocket: WebSocket is a full-duplex communication protocol that allows a persistent connection between a client and server and real-time two-way communication. Compared with HTTP requests, WebSocket provides lower latency and higher performance, and is suitable for scenarios that require real-time communication .84b03a472cdce1cb8659a5df9d43f857.png

  3. RESTful API: REST (Representational State Transfer) is a design style for building scalable web services. The RESTful API uses the HTTP protocol and follows a set of unified principles and conventions, making the communication between the front and back ends easier and more reliable.836f42fe95af7e170b523d3067672a26.png

  4. GraphQL: GraphQL is a query language and runtime environment for APIs that allows clients to explicitly request the data they need. Compared with the traditional RESTful API, GraphQL can avoid the problem of over-fetching or lack of data, and provide more accurate data transmission.25b798e10ea68726884ed0dcf588bfde.png

  5. Socket.IO: Socket.IO is a real-time application framework based on the WebSocket protocol and provides reliable two-way communication . It can transfer real-time data between client and server, and handle disconnection and reconnection issues.

Choosing an appropriate data format and transmission method depends on the specific application requirements and technology stack . JSON is usually the preferred data format in front-end and back-end interactions, while HTTP is the most commonly used transmission method. However, for real-time communication or highly scalable scenarios, other transports and protocols may need to be considered.

Front-end and back-end communication methods

In front-end and back-end communication, there are many ways to perform data interaction. Here are some common front-end and back-end communication methods:

  1. AJAX

  2. RESTful API

  3. WebSocket

  4. GraphQL

  5. Server-Sent Events (SSE): Server-Sent Events is an HTTP-based one-way communication technology that allows the server to push data to the client. The client receives the event stream from the server by establishing a persistent HTTP connection, realizing the ability of the server to actively send data to the client.a48ebb1fc91b9d3d85a70088fc5542d3.png

  6. Messaging Queue: Message Queuing is an asynchronous communication mechanism that allows data exchange between front and back ends by publishing and subscribing messages. Common message queuing systems include RabbitMQ and Apache Kafka, etc., which can be used to decouple front-end and back-end communication to achieve reliable message delivery.

ef167ed19f6b8c22ba620f0200cccd00.pngChoosing a suitable front-end and back-end communication method depends on the specific application requirements and technology stack. In general, RESTful API and AJAX are the most common ways to transfer and retrieve data. If real-time communication or finer-grained data control is required, technologies such as WebSocket and GraphQL can be considered.

Interface Design and Specification

Interface design and specification covers many aspects, here are some common interface design and specification points:

  1. Input and output: Clearly define the input and output of the interface, including the types, formats, and restrictions of parameters, and the structure and format of return values. Specifying clear inputs and outputs facilitates proper use of interfaces and accurate delivery of data.

  2. Methods and operations: Define the methods and operations supported by the interface, including obtaining data, creating resources, updating resources, deleting resources, etc. Each method should have a clear purpose and behavior, so that the caller can clearly understand when to use which method.

  3. Error Handling: Defines the behavior of the interface when an error or exceptional condition occurs. Including specifying the error code, the format and content of the error message, and the suggested error handling method, so that the caller can correctly handle the error situation.

  4. Authentication and permission: If the interface requires authentication and permission control, clearly specify the authentication method, token transfer method and access permission requirements. Ensure that only authorized users can access protected interfaces, and provide appropriate authentication and authorization mechanisms.

  5. Security and encryption: Specify the security requirements and encryption mechanism of the interface, such as using the HTTPS protocol for data transmission, encrypting sensitive information, and preventing cross-site scripting attacks, etc. Ensure the security and confidentiality of interfaces and data.

  6. Version control: If the interface is likely to change, consider using a version control mechanism to manage the evolution and backward compatibility of the interface. By adding the version number in the URL or request header, it ensures that different versions of the interface can coexist and provide backward compatibility.

  7. Interface documentation: Write detailed interface documentation, including interface descriptions, usage examples, parameter descriptions, return value descriptions, error code definitions, etc. Interface documentation helps developers understand and use interfaces correctly, and provides interface references and guidance.

  8. Performance and optimization: optimize the performance and efficiency of the interface, considering the data volume of requests and responses, network delays, concurrent processing capabilities, etc. Reasonably design the data transmission mode and data structure of the interface to provide efficient interface services.

  9. Consistency and standardization: Maintain consistency and standardization in interface design, follow industry and team best practices. Unify the naming convention, parameter passing method, response structure, etc. to improve the understandability and ease of use of the interface.

  10. Exception Handling: Define how the interface handles when abnormal conditions occur, such as network errors, database errors, etc. Reasonably handle exceptions and give clear error messages so that the caller can accurately understand the problem and take corresponding measures.

According to specific application scenarios and requirements, other aspects of design and specification may also be involved. It is important to ensure that the interface design is clear, consistent, and fully communicated and negotiated with the relevant teams to ensure effective use and successful interaction of the interface.

Cross-Origin Resource Sharing (CORS) and Security

Cross-Origin Resource Sharing (CORS)

Cross-Origin Resource Sharing (CORS) is a mechanism that allows the use of additional HTTP headers in the browser to allow the server to decide whether to allow access to cross-origin requests. CORS is mainly used to solve the same-origin policy restrictions of browsers, so that front-end applications in different domains can communicate with back-end servers safely across domains.

The same-origin policy is a browser security policy that restricts access between pages of different origins (protocols, domain names, ports). For example, if a page is loaded from the example.com domain name, its JavaScript code can only access resources from the same domain name, and cannot directly access resources from other domain names.

CORS works as follows:

  1. When a browser initiates a cross-domain request, it will add an Origin field to the request header to indicate the source (domain) of the request.

  2. After the server receives the cross-domain request, it will check the Origin field and add some specific CORS header fields in the response header to tell the browser whether to allow access to the cross-domain request.

  3. After the browser receives the response, it will judge according to the CORS header field in the response header. If the server allows cross-domain access, the browser will continue to process the response, otherwise it will throw an error.

The security of CORS is controlled by the server . The server can specify the allowed cross-domain request sources, allowed HTTP methods, allowed custom headers, etc. by setting the CORS header field in the response header.

safety

During the design and development process, the following security-related considerations need to be noted:

  1. Restricting cross-domain access: The server can set the CORS header field to restrict the access of cross-domain requests according to actual needs. For example, you can specify that only specific domain names are allowed to access, or only specific HTTP methods are allowed.

  2. Authentication and authorization: Cross-domain requests may involve sensitive data or operations, so authentication and authorization must be performed on the server side to ensure that only authorized users can make cross-domain requests.

  3. Prevent cross-site request forgery (CSRF) attacks: CORS cannot completely prevent cross-domain requests, so when designing web applications, other security measures need to be taken, such as using CSRF token protection to prevent cross-site request forgery attacks.

  4. Secure transmission: For cross-domain requests involving sensitive data, the HTTPS protocol should be used for secure transmission to protect the confidentiality and integrity of the data.

Through reasonable configuration and use of CORS and other security measures, the security of cross-domain requests can be ensured, and the required cross-domain data exchange can be realized in front-end and back-end interactions.

- END -

About Qi Wu Troupe

Qi Wu Troupe is the largest front-end team of 360 Group, and participates in the work of W3C and ECMA members (TC39) on behalf of the group. Qi Wu Troupe attaches great importance to talent training, and has various development directions such as engineers, lecturers, translators, business interface people, and team leaders for employees to choose from, and provides corresponding technical, professional, general, and leadership training course. Qi Dance Troupe welcomes all kinds of outstanding talents to pay attention to and join Qi Dance Troupe with an open and talent-seeking attitude.

0c06631d6b94100dd01827a980c89046.png

Guess you like

Origin blog.csdn.net/qiwoo_weekly/article/details/131335825