HTTP常见的请求头有哪些?都有什么作用?在 Web 应用中使用这些请求头?

HTTP常见的请求头有哪些?都有什么作用?在 Web 应用中使用这些请求头?

HTTP 请求头(Request Headers)用于在 HTTP 请求中携带额外的信息,帮助服务器更好地处理请求。以下是一些常见的 HTTP 请求头及其作用:

常见请求头及其作用

1. Accept

作用:告知服务器客户端可以接受的内容类型。示例:Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8说明:客户端可以接受多种内容类型,优先级由 q 参数决定。

2. Accept-Encoding

作用:告知服务器客户端支持的压缩编码方式。示例:Accept-Encoding: gzip, deflate, br说明:客户端支持 gzip、deflate 和 brotli 压缩。

3. Accept-Language

作用:告知服务器客户端首选的语言。示例:Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8说明:客户端首选英语(美国),其次是英语(通用),最后是中文(简体)。

4. Authorization

作用:用于向服务器提供认证信息,通常用于 Basic 认证或 Bearer Token。示例:Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...说明:使用 Bearer Token 进行认证。

5. Content-Length

作用:告知服务器请求体的长度(以字节为单位)。示例:Content-Length: 348说明:请求体的长度为 348 字节。

6. Content-Type

作用:告知服务器请求体的内容类型。示例:Content-Type: application/json说明:请求体是 JSON 格式的数据。

7. Cookie

作用:用于发送存储在客户端的 cookie 信息。示例:Cookie: session_id=123456; user_id=7890说明:发送两个 cookie:session_id 和 user_id。

8. Host

作用:指定请求的主机名和端口号。示例:Host: www.example.com:8080说明:请求的目标主机是 www.example.com,端口号是 8080。

9. Referer

作用:告知服务器当前请求是从哪个页面跳转过来的。示例:Referer: https://www.example.com/page1说明:当前请求是从 https://www.example.com/page1 页面跳转过来的。

10. User-Agent

作用:告知服务器客户端的浏览器和操作系统信息。示例:User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3说明:客户端使用的是 Chrome 浏览器,操作系统是 Windows 10。

11. Cache-Control

作用:控制缓存行为。示例:Cache-Control: no-cache说明:要求不使用缓存,每次都从服务器获取最新数据。

12. Connection

作用:控制连接的状态。示例:Connection: keep-alive说明:保持连接打开,以便后续请求可以复用同一连接。

13. If-Modified-Since

作用:告知服务器只有在指定日期之后被修改的资源才会返回。示例:If-Modified-Since: Wed, 21 Oct 2015 07:28:00 GMT说明:只有在 2015 年 10 月 21 日 07:28:00 GMT 之后被修改的资源才会返回。

14. If-None-Match

作用:告知服务器只有在实体标签(ETag)不匹配时才返回资源。示例:If-None-Match: "67ab4321cd8e"说明:只有在 ETag 不等于 "67ab4321cd8e" 时才返回资源。

15. Origin

作用:用于 CORS(跨域资源共享)请求,告知服务器请求的来源。示例:Origin: https://www.example.com说明:请求的来源是 https://www.example.com。

16. Range

作用:请求资源的一部分。示例:Range: bytes=0-1023说明:请求资源的前 1024 字节。

17. Upgrade

作用:请求升级到另一种协议,通常用于 WebSocket 协议。示例:Upgrade: websocket说明:请求将连接升级到 WebSocket 协议。

18. Sec-WebSocket-Key

作用:用于 WebSocket 握手,生成一个随机的密钥。示例:Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==说明:生成的随机密钥。

19. Sec-WebSocket-Version

作用:告知服务器 WebSocket 协议的版本。示例:Sec-WebSocket-Version: 13说明:使用 WebSocket 协议的第 13 版。

20. X-Requested-With

作用:告知服务器请求是由 AJAX 发起的。示例:X-Requested-With: XMLHttpRequest说明:请求是由 XMLHttpRequest 发起的。

如何在 Web 应用中使用这些请求头

前端(JavaScript/TypeScript)

使用 Fetch API

Fetch API 是现代浏览器提供的原生方法,用于发起 HTTP 请求。你可以通过 headers 选项来设置请求头。

fetch('https://api.example.com/data', {

method: 'GET',

headers: {

'Accept': 'application/json',

'Authorization': 'Bearer your-token',

'User-Agent': 'MyApp/1.0'

}

})

.then(response => response.json())

.then(data => console.log(data))

.catch(error => console.error('Error:', error));

使用 Axios

Axios 是一个流行的 HTTP 客户端库,支持浏览器和 Node.js。你也可以通过 headers 选项来设置请求头。

import axios from 'axios';

axios.get('https://api.example.com/data', {

headers: {

'Accept': 'application/json',

'Authorization': 'Bearer your-token',

'User-Agent': 'MyApp/1.0'

}

})

.then(response => {

console.log(response.data);

})

.catch(error => {

console.error('Error:', error);

});

后端(Node.js/Express)

使用 Express

在 Express 中,你可以通过 res.set 方法来设置响应头,或者通过 req.headers 来访问请求头。

const express = require('express');

const app = express();

app.get('/data', (req, res) => {

// 访问请求头

const authorization = req.headers.authorization;

// 设置响应头

res.set({

'Content-Type': 'application/json',

'Cache-Control': 'no-cache'

});

// 发送响应

res.send({ message: 'Hello, World!', authorization });

});

app.listen(3000, () => {

console.log('Server is running on port 3000');

});

后端(Python/Flask)

使用 Flask

在 Flask 中,你可以通过 request.headers 来访问请求头,通过 response.headers 来设置响应头。

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/data')

def get_data():

# 访问请求头

authorization = request.headers.get('Authorization')

# 创建响应

response = jsonify({

'message': 'Hello, World!',

'authorization': authorization

})

# 设置响应头

response.headers['Content-Type'] = 'application/json'

response.headers['Cache-Control'] = 'no-cache'

return response

if __name__ == '__main__':

app.run(port=3000)

常见请求头的使用示例

1. Authorization

在前端发起请求时,设置 Authorization 头:

fetch('https://api.example.com/data', {

method: 'GET',

headers: {

'Authorization': 'Bearer your-token'

}

})

.then(response => response.json())

.then(data => console.log(data))

.catch(error => console.error('Error:', error));

在后端访问 Authorization 头:

app.get('/data', (req, res) => {

const authorization = req.headers.authorization;

// 处理请求

});

2. Content-Type

在前端设置 Content-Type 头:

fetch('https://api.example.com/data', {

method: 'POST',

headers: {

'Content-Type': 'application/json'

},

body: JSON.stringify({ key: 'value' })

})

.then(response => response.json())

.then(data => console.log(data))

.catch(error => console.error('Error:', error));

在后端访问 Content-Type 头:

app.post('/data', (req, res) => {

const contentType = req.headers['content-type'];

// 处理请求

});

3. Cache-Control

在后端设置 Cache-Control 头:

app.get('/data', (req, res) => {

res.set({

'Cache-Control': 'no-cache'

});

res.send({ message: 'Hello, World!' });

});

4. Accept

在前端设置 Accept 头:

fetch('https://api.example.com/data', {

method: 'GET',

headers: {

'Accept': 'application/json'

}

})

.then(response => response.json())

.then(data => console.log(data))

.catch(error => console.error('Error:', error));

在后端访问 Accept 头:

app.get('/data', (req, res) => {

const accept = req.headers.accept;

// 处理请求

});

总结

通过上述示例,你可以看到如何在前端和后端使用常见的 HTTP 请求头。这些请求头在实际应用中非常有用,可以帮助你更好地控制请求和响应的行为,提高应用的性能和安全性。希望这些示例对你有所帮助!

相关数据