HTTP 请求头(Request Headers)用于在 HTTP 请求中携带额外的信息,帮助服务器更好地处理请求。以下是一些常见的 HTTP 请求头及其作用:
1. Accept
2. Accept-Encoding
3. Accept-Language
4. Authorization
5. Content-Length
6. Content-Type
7. Cookie
8. Host
9. Referer
10. User-Agent
11. Cache-Control
12. Connection
13. If-Modified-Since
14. If-None-Match
15. Origin
16. Range
17. Upgrade
18. Sec-WebSocket-Key
19. Sec-WebSocket-Version
20. X-Requested-With
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 请求头。这些请求头在实际应用中非常有用,可以帮助你更好地控制请求和响应的行为,提高应用的性能和安全性。希望这些示例对你有所帮助!