avatar
Siz Long

My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • Resume
  • Archives
  • Categories
  • Photos
  • Music



{{ date }}

{{ time }}

avatar
Siz Long

My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • 主页
  • Resume
  • Archives
  • Categories
  • Photos
  • Music

Network Protocols for Frontend Developers

  2023-06-15        
字数统计: 2.3k字   |   阅读时长: 14min

Network Protocols for Frontend Developers

Understanding network protocols is essential for frontend developers to build efficient and secure web applications. This guide covers the key network protocols and concepts relevant to frontend development.

HTTP (Hypertext Transfer Protocol)

HTTP is the foundation of data communication on the web.

HTTP Basics

  • Client-Server Model: Client (browser) sends requests to server, which responds with resources
  • Stateless Protocol: Each request-response pair is independent
  • Text-Based: Messages are human-readable

HTTP Request Structure

1
2
3
4
5
GET /path/to/resource HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)
Accept: text/html
Accept-Language: en-US,en;q=0.9

Components:

  1. Request Line: Method, URI, HTTP Version
  2. Headers: Metadata about the request
  3. Body (optional): Data sent to the server

HTTP Response Structure

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
HTTP/1.1 200 OK
Date: Mon, 23 May 2023 22:38:34 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 138
Cache-Control: max-age=3600

<!DOCTYPE html>
<html>
<head>
<title>Example Page</title>
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>

Components:

  1. Status Line: HTTP Version, Status Code, Reason Phrase
  2. Headers: Metadata about the response
  3. Body (optional): The requested resource

HTTP Methods

Method Purpose Idempotent Safe
GET Retrieve data Yes Yes
POST Submit data No No
PUT Update/Replace data Yes No
DELETE Remove data Yes No
PATCH Partially update data No No
HEAD Get headers only Yes Yes
OPTIONS Get supported methods Yes Yes

HTTP Status Codes

Range Category Examples
1xx Informational 100 Continue, 101 Switching Protocols
2xx Success 200 OK, 201 Created, 204 No Content
3xx Redirection 301 Moved Permanently, 302 Found, 304 Not Modified
4xx Client Error 400 Bad Request, 401 Unauthorized, 404 Not Found
5xx Server Error 500 Internal Server Error, 503 Service Unavailable

HTTP/1.1 vs HTTP/2 vs HTTP/3

HTTP/1.1

  • Text-based protocol
  • One request per connection (head-of-line blocking)
  • Requires multiple TCP connections for parallelism
1
2
3
4
5
6
7
8
9
10
11
// Sequential requests in HTTP/1.1
fetch('/api/data1')
.then(response => response.json())
.then(data => {
// Process data1
return fetch('/api/data2');
})
.then(response => response.json())
.then(data => {
// Process data2
});

HTTP/2

  • Binary protocol
  • Multiplexed streams (multiple requests over single connection)
  • Server push capabilities
  • Header compression
1
2
3
4
5
6
7
8
9
// Concurrent requests benefit from HTTP/2 multiplexing
Promise.all([
fetch('/api/data1').then(response => response.json()),
fetch('/api/data2').then(response => response.json()),
fetch('/api/data3').then(response => response.json())
])
.then(([data1, data2, data3]) => {
// Process all data at once
});

HTTP/3

  • Uses QUIC transport protocol instead of TCP
  • Improved performance on unreliable networks
  • Reduced connection establishment time
  • Better multiplexing without head-of-line blocking

HTTPS (HTTP Secure)

HTTPS is HTTP over TLS/SSL encryption, providing:

  • Data encryption
  • Server authentication
  • Message integrity

How HTTPS Works

  1. TLS Handshake: Client and server establish encryption parameters
  2. Certificate Validation: Browser verifies server’s identity
  3. Secure Communication: Data is encrypted using session keys

Certificates and Certificate Authorities (CAs)

  • Digital certificates establish trust in a website
  • CAs validate and issue certificates
  • Browsers maintain a list of trusted CAs

HTTPS Best Practices

  • Enforce HTTPS across your entire site
  • Use HTTP Strict Transport Security (HSTS)
  • Keep certificates up to date
  • Use secure cookies
1
2
<!-- Content Security Policy for HTTPS enforcement -->
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">

Web Caching

Caching improves performance by storing copies of resources.

Browser Cache

1
2
3
Cache-Control: max-age=3600, must-revalidate
ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4"
Last-Modified: Wed, 21 Oct 2015 07:28:00 GMT
  • Controlled via HTTP headers
  • Caches resources locally
  • Reduces network requests and latency

Cache-Control Header Options

  • max-age: Duration in seconds the resource is fresh
  • no-cache: Revalidate before using cached copy
  • no-store: Don’t cache at all
  • public: Any cache can store the response
  • private: Only browser can cache the response

ETag and Conditional Requests

1
2
3
4
5
6
7
8
9
10
11
12
13
// Browser automatically uses ETag with fetch
fetch('/api/data', {
headers: {
'If-None-Match': 'W/"previousEtagValue"'
}
})
.then(response => {
if (response.status === 304) {
// Use cached data
return getCachedData();
}
return response.json();
});
  • ETag: Unique identifier for resource version
  • If-None-Match: Sends previous ETag to check if resource changed
  • 304 Not Modified: Server responds if resource hasn’t changed

RESTful API

REST (Representational State Transfer) is an architectural style for designing networked applications.

Key Principles

  • Resource-Based: URIs identify resources
  • Stateless: No client context stored on server
  • Uniform Interface: Consistent resource handling
  • CRUD Operations: Map to HTTP methods

RESTful Endpoint Design

1
2
3
4
5
6
7
GET /users                 # Get all users
GET /users/123 # Get user with ID 123
POST /users # Create new user
PUT /users/123 # Update user 123
PATCH /users/123 # Partially update user 123
DELETE /users/123 # Delete user 123
GET /users/123/orders # Get orders for user 123

Example RESTful API Call

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Creating a new user
fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer token123'
},
body: JSON.stringify({
name: 'John Doe',
email: 'john@example.com'
})
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error ${response.status}`);
}
return response.json();
})
.then(data => console.log('User created:', data))
.catch(error => console.error('Error:', error));

Cross-Origin Resource Sharing (CORS)

CORS is a security feature that restricts web pages from making requests to a different domain.

Same-Origin Policy

Browsers restrict cross-origin HTTP requests as a security measure.

CORS Headers

1
2
3
4
5
Access-Control-Allow-Origin: https://example.com
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 3600

Simple vs Preflight Requests

Simple Requests meet all these conditions:

  • Uses GET, HEAD, or POST
  • Only uses CORS-safe headers
  • Content-Type is application/x-www-form-urlencoded, multipart/form-data, or text/plain

Preflight Requests:

  • Browser sends OPTIONS request before actual request
  • Server must respond with appropriate CORS headers
  • Actual request proceeds only if preflight succeeds
1
2
3
4
5
6
7
8
9
// This will trigger a preflight request due to custom header
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json', // Non-simple content type
'X-Custom-Header': 'value' // Custom header
},
body: JSON.stringify({ key: 'value' })
});

CORS in Frontend Development

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Using mode: 'cors' explicitly (default for fetch)
fetch('https://api.example.com/data', {
mode: 'cors',
credentials: 'include' // Send cookies cross-origin
});

// Using proxy in development
// In package.json for React apps
{
"proxy": "https://api.example.com"
}

// Then in code
fetch('/data'); // Requests go to proxy

WebSockets

WebSockets provide full-duplex communication channels over a single TCP connection.

Key Characteristics

  • Persistent Connection: Stays open until closed
  • Bi-directional: Server and client can send messages
  • Low Latency: Less overhead than HTTP
  • Cross-Origin Compatible: With proper CORS headers

WebSocket Handshake

Client initiates with HTTP upgrade request:

1
2
3
4
5
6
GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13

Using WebSockets in JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Creating a WebSocket connection
const socket = new WebSocket('wss://echo.websocket.org');

// Connection opened
socket.addEventListener('open', (event) => {
console.log('Connected to WebSocket server');
socket.send('Hello Server!');
});

// Listen for messages
socket.addEventListener('message', (event) => {
console.log('Message from server:', event.data);
});

// Listen for errors
socket.addEventListener('error', (event) => {
console.error('WebSocket error:', event);
});

// Connection closed
socket.addEventListener('close', (event) => {
console.log('Connection closed', event.code, event.reason);
});

// Close the connection when done
function closeConnection() {
socket.close(1000, "Deliberately closed");
}

WebSocket vs HTTP

Feature WebSocket HTTP/REST
Connection Persistent New connection per request
Communication Bi-directional Request-response
Overhead Low after handshake Headers with each request
Use Case Real-time updates CRUD operations

Server-Sent Events (SSE)

SSE allows servers to push updates to the browser.

Key Features

  • Unidirectional: Server to client only
  • Auto-reconnection: Built-in reconnection
  • Text-based: Uses HTTP for transport
  • Simpler than WebSockets: For one-way communication

Using Server-Sent Events

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Creating an EventSource
const eventSource = new EventSource('/events');

// Listen for all messages
eventSource.onmessage = (event) => {
console.log('New message:', event.data);
};

// Listen for specific event types
eventSource.addEventListener('update', (event) => {
console.log('Update event:', event.data);
});

// Error handling
eventSource.onerror = (error) => {
console.error('EventSource error:', error);
if (eventSource.readyState === EventSource.CLOSED) {
console.log('Connection closed');
}
};

// Close the connection when done
function closeSSE() {
eventSource.close();
}

GraphQL

GraphQL is a query language for APIs and a runtime for fulfilling those queries.

Key Concepts

  • Single Endpoint: One endpoint for all requests
  • Request Exactly What You Need: No over/under-fetching
  • Strongly Typed: Schema defines available data
  • Introspective: Query schema for information

Basic GraphQL Query

1
2
3
4
5
6
7
8
9
10
11
query {
user(id: "123") {
id
name
email
posts {
title
content
}
}
}

Using GraphQL with Fetch

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// GraphQL query with variables
const query = `
query GetUser($id: ID!) {
user(id: $id) {
id
name
email
}
}
`;

fetch('https://api.example.com/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer token123'
},
body: JSON.stringify({
query,
variables: { id: '123' }
})
})
.then(res => res.json())
.then(result => {
console.log(result.data.user);
});

DNS (Domain Name System)

DNS translates domain names to IP addresses.

DNS Resolution Process

  1. Browser checks its cache
  2. OS checks its cache
  3. Router checks its cache
  4. ISP’s DNS server is queried
  5. If not found, query goes to root servers
  6. Root server directs to TLD server
  7. TLD server directs to authoritative nameserver
  8. IP address is returned

DNS Record Types

  • A Record: Maps domain to IPv4 address
  • AAAA Record: Maps domain to IPv6 address
  • CNAME: Canonical name record (alias)
  • MX: Mail exchange record
  • TXT: Text record for various purposes
  • NS: Nameserver record

DNS and Web Performance

  • DNS Prefetching: Pre-resolve domains user might visit
1
2
<link rel="dns-prefetch" href="https://fonts.googleapis.com">
<link rel="dns-prefetch" href="https://analytics.example.com">

CDN (Content Delivery Network)

CDNs distribute content to servers worldwide to reduce latency.

How CDNs Work

  1. User requests content
  2. Request routed to nearest CDN edge server
  3. Edge server checks cache
  4. If found, content is served from cache
  5. If not found, CDN fetches from origin server

Benefits of CDNs

  • Reduced latency
  • Decreased server load
  • Improved availability
  • DDoS protection

Using CDNs for Frontend Resources

1
2
3
4
5
<!-- Loading jQuery from a CDN -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<!-- Using a CSS framework from a CDN -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">

CDN Best Practices

  • Use multiple CDNs for redundancy
  • Set appropriate cache headers
  • Use subresource integrity (SRI)
  • Consider CDN fallbacks
1
2
3
4
5
6
7
8
9
10
11
<!-- Using SRI with a CDN resource -->
<script
src="https://cdn.example.com/library.js"
integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"
crossorigin="anonymous">
</script>

<!-- With local fallback -->
<script>
window.jQuery || document.write('<script src="/js/jquery.min.js"><\/script>');
</script>

Network Performance Optimization

Reducing Request Count

  • Bundle assets
  • Use CSS sprites
  • Inline critical CSS/JS
  • Use icon fonts or SVG

Reducing File Size

  • Minify CSS, JavaScript, HTML
  • Compress images
  • Use HTTP compression (gzip, Brotli)
  • Use modern image formats (WebP, AVIF)

Connection Optimization

  • Use HTTP/2 or HTTP/3
  • Enable keep-alive
  • DNS prefetching
  • Preconnect to critical origins
1
2
3
<!-- Preconnect to origins -->
<link rel="preconnect" href="https://example.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>

Resource Hints

1
2
3
4
5
6
7
8
<!-- Prefetch: low-priority fetch for future navigation -->
<link rel="prefetch" href="/page-that-user-will-visit-next.html">

<!-- Preload: high-priority fetch for current page -->
<link rel="preload" href="/fonts/font.woff2" as="font" type="font/woff2" crossorigin>

<!-- Prerender: fetch and render in background -->
<link rel="prerender" href="/likely-next-page.html">

Debugging Network Issues

Browser DevTools

  • Network Panel: Monitor requests, timing, headers
  • Performance Panel: Analyze loading performance
  • Application Panel: Inspect storage, cache, service workers

Common Network Issues

  1. CORS Errors: Missing or incorrect headers
  2. Mixed Content: HTTP resources on HTTPS page
  3. Blocked Requests: Browser security, extensions, CSP
  4. Slow Performance: Large payloads, many requests
  5. Certificate Errors: Invalid or expired certificates

Network Testing Tools

  • WebPageTest: Detailed performance analysis
  • Lighthouse: Performance, accessibility, SEO audits
  • Postman/Insomnia: API testing
  • Wireshark: Deep packet inspection
  • Ping/Traceroute: Basic connectivity testing

Learning Resources

  • MDN HTTP Documentation
  • Google Web Fundamentals: Networking
  • High Performance Browser Networking by Ilya Grigorik
  • HTTP/3 Explained by Daniel Stenberg
  • Web.dev: Network Reliability
  • Cloudflare Learning Center

Understanding these network protocols and concepts is essential for building fast, reliable, and secure web applications. As a frontend developer, this knowledge helps you make informed decisions about how to structure your applications and optimize network performance.

  • Web Development
  • HTTP
  • HTTPS
  • WebSockets
  • REST
  • Network

扫一扫,分享到微信

微信分享二维码
Frontend Performance Optimization
Web Security
目录
  1. 1. Network Protocols for Frontend Developers
    1. 1.1. HTTP (Hypertext Transfer Protocol)
      1. 1.1.1. HTTP Basics
      2. 1.1.2. HTTP Request Structure
      3. 1.1.3. HTTP Response Structure
      4. 1.1.4. HTTP Methods
      5. 1.1.5. HTTP Status Codes
      6. 1.1.6. HTTP/1.1 vs HTTP/2 vs HTTP/3
        1. 1.1.6.1. HTTP/1.1
        2. 1.1.6.2. HTTP/2
        3. 1.1.6.3. HTTP/3
    2. 1.2. HTTPS (HTTP Secure)
      1. 1.2.1. How HTTPS Works
      2. 1.2.2. Certificates and Certificate Authorities (CAs)
      3. 1.2.3. HTTPS Best Practices
    3. 1.3. Web Caching
      1. 1.3.1. Browser Cache
      2. 1.3.2. Cache-Control Header Options
      3. 1.3.3. ETag and Conditional Requests
    4. 1.4. RESTful API
      1. 1.4.1. Key Principles
      2. 1.4.2. RESTful Endpoint Design
      3. 1.4.3. Example RESTful API Call
    5. 1.5. Cross-Origin Resource Sharing (CORS)
      1. 1.5.1. Same-Origin Policy
      2. 1.5.2. CORS Headers
      3. 1.5.3. Simple vs Preflight Requests
      4. 1.5.4. CORS in Frontend Development
    6. 1.6. WebSockets
      1. 1.6.1. Key Characteristics
      2. 1.6.2. WebSocket Handshake
      3. 1.6.3. Using WebSockets in JavaScript
      4. 1.6.4. WebSocket vs HTTP
    7. 1.7. Server-Sent Events (SSE)
      1. 1.7.1. Key Features
      2. 1.7.2. Using Server-Sent Events
    8. 1.8. GraphQL
      1. 1.8.1. Key Concepts
      2. 1.8.2. Basic GraphQL Query
      3. 1.8.3. Using GraphQL with Fetch
    9. 1.9. DNS (Domain Name System)
      1. 1.9.1. DNS Resolution Process
      2. 1.9.2. DNS Record Types
      3. 1.9.3. DNS and Web Performance
    10. 1.10. CDN (Content Delivery Network)
      1. 1.10.1. How CDNs Work
      2. 1.10.2. Benefits of CDNs
      3. 1.10.3. Using CDNs for Frontend Resources
      4. 1.10.4. CDN Best Practices
    11. 1.11. Network Performance Optimization
      1. 1.11.1. Reducing Request Count
      2. 1.11.2. Reducing File Size
      3. 1.11.3. Connection Optimization
      4. 1.11.4. Resource Hints
    12. 1.12. Debugging Network Issues
      1. 1.12.1. Browser DevTools
      2. 1.12.2. Common Network Issues
      3. 1.12.3. Network Testing Tools
    13. 1.13. Learning Resources

150 篇 | 131.7k
次 | 人
这里自动载入天数这里自动载入时分秒
2022-2025 loong loong | 新南威尔士龙龙号