HTTP 请求头(Request Headers)用于在 HTTP 请求中携带额外的信息,帮助服务器更好地处理请求。以下是一些常见的 HTTP 请求头及其作用:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
q
参数决定。Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Content-Length: 348
Content-Type: application/json
Cookie: session_id=123456; user_id=7890
session_id
和 user_id
。Host: www.example.com:8080
www.example.com
,端口号是 8080
。Referer: https://www.example.com/page1
https://www.example.com/page1
页面跳转过来的。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
Cache-Control: no-cache
Connection: keep-alive
If-Modified-Since: Wed, 21 Oct 2015 07:28:00 GMT
If-None-Match: "67ab4321cd8e"
"67ab4321cd8e"
时才返回资源。Origin: https://www.example.com
https://www.example.com
。Range: bytes=0-1023
Upgrade: websocket
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
X-Requested-With: XMLHttpRequest
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 是一个流行的 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);
});
在 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');
});
在 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)
在前端发起请求时,设置 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;
// 处理请求
});
在前端设置 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'];
// 处理请求
});
在后端设置 Cache-Control
头:
app.get('/data', (req, res) => {
res.set({
'Cache-Control': 'no-cache'
});
res.send({ message: 'Hello, World!' });
});
在前端设置 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 请求头。这些请求头在实际应用中非常有用,可以帮助你更好地控制请求和响应的行为,提高应用的性能和安全性。希望这些示例对你有所帮助!