每次调试接口,总是少不了http响应头,请求头的参数信息,什么跨域啦,什么格式不对啦,还有什么认证信息,都发生在请求头或者响应头里面。今天这篇文章就来总结下常见的http请求头和响应头。
请求头和响应头是 HTTP 协议中非常重要的组成部分,它们提供了关于请求和响应的额外信息。
常见请求头
- Host
- 含义:指定请求的主机和端口号。在 HTTP/1.1 中是必需的。
示例:Host: www.example.com:8080
- 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
- Accept
- 含义:客户端能够处理的媒体类型。
示例:Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
- Accept-Language
- 含义:客户端可接受的语言。
示例:Accept-Language: en-US,en;q=0.5
- Accept-Encoding
- 含义:客户端可接受的编码方式。
示例:Accept-Encoding: gzip, deflate
- Content-Type
- 含义:请求体的媒体类型。
示例:Content-Type: application/json
- Content-Length
- 含义:请求体的长度。
示例:Content-Length: 24
- Authorization
- 含义:用于 HTTP 认证的凭据。
示例:Authorization: Bearer your_access_token
- Referer
- 含义:请求的来源 URL。
示例:Referer: http://www.example.com/index.html
- Connection
- 含义:控制连接的持久性。
示例:Connection: keep-alive
常见响应头
- Content-Type
- 含义:响应体的媒体类型。
示例:Content-Type: text/html; charset=UTF-8
- Content-Length
- 含义:响应体的长度。
示例:Content-Length: 1234
- Content-Encoding
- 含义:响应体的编码方式。
示例:Content-Encoding: gzip
- Content-Language
- 含义:响应体的语言。
示例:Content-Language: en-US
- Content-Disposition
- 含义:指示如何处理响应的内容,如附件下载。
- 示例:Content-Disposition: attachment; filename="example.txt"
- Server
- 含义:服务器软件的信息。
示例:Server: Apache/2.4.1 (Unix)
- Date
- 含义:响应生成的日期和时间。
示例:Date: Mon, 1 Jan 2024 00:00:00 GMT
- Last-Modified
- 含义:资源最后修改的日期和时间。
示例:Last-Modified: Mon, 1 Jan 2024 00:00:00 GMT
- ETag
- 含义:资源的特定版本的标识符。
示例:ETag: "33a64df559642d693a60909b83f4ab229"
- Cache-Control
- 含义:指定缓存机制。
示例:Cache-Control: no-cache
示例代码(Node.js Express)
以下是一个使用 Node.js 和 Express 框架的示例,展示了如何设置请求头和响应头:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
// 设置响应头
res.set({
'Content-Type': 'text/plain',
'Content-Length': '12',
'Content-Language': 'en-US',
'Cache-Control': 'no-cache',
'Server': 'MyCustomServer'
});
// 发送响应
res.send('Hello, World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
创作不易,如果这篇文章对你有用,欢迎点赞关注加评论哦
小伙伴们在工作中还遇到过其他应用场景吗,欢迎评论区留言讨论哦。
本文暂时没有评论,来添加一个吧(●'◡'●)