【WEB开发.js】HTTP请求和相应报文的头字段:Content-Type (巨巨巨巨详细好懂的举例详解)

Content-Type 是 HTTP 请求和响应报文中的头字段之一,用于指定发送的数据类型(MIME 类型)。它告诉服务器或客户端数据的格式,方便接收方正确解析和处理内容。

例如,在发送 JSON 数据时,会指定 Content-Type: application/json;而发送 HTML 页面时,则会指定 Content-Type: text/html

常见的 Content-Type 类型

1. 文本类
  • text/plain:纯文本。
  • text/html:HTML 文档。
  • text/css:CSS 样式表。
  • text/javascript:JavaScript 文件。
2. 应用类
  • application/json:JSON 格式数据,适合传输复杂结构。
  • application/x-www-form-urlencoded:键值对格式,常用于表单数据提交。
  • application/xml:XML 格式数据。
  • application/octet-stream:二进制数据流(任意文件类型,通常用于下载)。
3. 多媒体类
  • image/png:PNG 图片。
  • image/jpeg:JPEG 图片。
  • audio/mpeg:MP3 音频。
  • video/mp4:MP4 视频。
4. 特殊用途
  • multipart/form-data
    • 用于上传文件或表单数据。
    • 边界(boundary)标识数据段的分隔。
  • application/pdf:PDF 文件。

举例详解~~

1. application/json

用途
  • 用于发送或接收 JSON 格式数据。
  • 适合传输复杂数据(如嵌套对象、数组)。
前端(fetch
fetch('/api/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ name: 'Alice', age: 30 })
})
  .then(response => response.json())
  .then(data => console.log(data));
后端(Python Flask)
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/api/data', methods=['POST'])
def receive_json():
    data = request.get_json()  # 解析 JSON 数据
    print(data)  # {'name': 'Alice', 'age': 30}
    return jsonify({"status": "success", "received": data})

if __name__ == '__main__':
    app.run()

2. application/x-www-form-urlencoded

用途
  • 常用于表单数据提交。
  • 数据编码成 key=value&key=value 的形式,适合简单键值对。
前端(fetch
const formData = new URLSearchParams();
formData.append('name', 'Alice');
formData.append('age', '30');

fetch('/api/form', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  body: formData.toString()
})
  .then(response => response.text())
  .then(data => console.log(data));
后端(Python Flask)
@app.route('/api/form', methods=['POST'])
def receive_form():
    data = request.form  # 获取表单数据
    print(data)  # ImmutableMultiDict([('name', 'Alice'), ('age', '30')])
    return f"Received: {data.to_dict()}"

3. multipart/form-data

用途
  • 用于上传文件和表单数据。
  • 数据分段发送,每段都有自己的边界(boundary)。
前端(fetch
const formData = new FormData();
formData.append('name', 'Alice');
formData.append('file', new File(['Hello'], 'hello.txt'));

fetch('/api/upload', {
  method: 'POST',
  body: formData // 不需要手动设置 Content-Type,浏览器会自动添加
})
  .then(response => response.text())
  .then(data => console.log(data));
后端(Python Flask)
@app.route('/api/upload', methods=['POST'])
def upload_file():
    name = request.form.get('name')  # 获取普通字段
    file = request.files.get('file')  # 获取文件对象
    print(f"Name: {name}, Filename: {file.filename}")
    return f"File {file.filename} received."

4. text/plain

用途
  • 用于发送纯文本数据。
  • 数据直接是字符串,无需额外格式化。
前端(fetch
fetch('/api/plain', {
  method: 'POST',
  headers: {
    'Content-Type': 'text/plain'
  },
  body: 'Hello, this is plain text!'
})
  .then(response => response.text())
  .then(data => console.log(data));
后端(Python Flask)
@app.route('/api/plain', methods=['POST'])
def plain_text():
    data = request.data.decode('utf-8')  # 获取原始数据并解码
    print(data)  # Hello, this is plain text!
    return f"Received plain text: {data}"

5. text/html

用途
  • 用于返回 HTML 页面。
  • 适合前端动态展示 HTML 内容。
前端(请求示例)
fetch('/api/html', {
  method: 'GET'
})
  .then(response => response.text())
  .then(html => document.body.innerHTML = html);
后端(Python Flask)
@app.route('/api/html', methods=['GET'])
def return_html():
    html_content = """
    <html>
        <body>
            <h1>Welcome to my site</h1>
        </body>
    </html>
    """
    return html_content, 200, {'Content-Type': 'text/html'}

6. application/octet-stream

用途
  • 用于传输任意二进制数据(如文件下载)。
  • 适合需要客户端保存的数据。
前端(下载文件)
fetch('/api/download')
  .then(response => response.blob())
  .then(blob => {
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'example.bin'; // 保存的文件名
    a.click();
  });
后端(Python Flask)
@app.route('/api/download', methods=['GET'])
def download_file():
    with open('example.bin', 'rb') as f:
        file_data = f.read()
    return file_data, 200, {'Content-Type': 'application/octet-stream'}

7. image/png(或其他图片类型)

用途
  • 用于传输图片数据。
前端(请求图片)
fetch('/api/image')
  .then(response => response.blob())
  .then(blob => {
    const img = document.createElement('img');
    img.src = URL.createObjectURL(blob);
    document.body.appendChild(img);
  });
后端(Python Flask)
@app.route('/api/image', methods=['GET'])
def send_image():
    with open('image.png', 'rb') as f:
        image_data = f.read()
    return image_data, 200, {'Content-Type': 'image/png'}

总结

Content-Type用途前端常用方法后端处理方式
application/jsonJSON 数据JSON.stringify()request.get_json()
application/x-www-form-urlencoded表单键值对数据URLSearchParams()request.form
multipart/form-data文件和表单混合数据FormData()request.files + request.form
text/plain纯文本数据直接传字符串request.data.decode()
text/htmlHTML 内容response.text()返回字符串并设置 Content-Type
application/octet-stream二进制数据(文件下载)response.blob()读取文件并设置 Content-Type
image/png图片数据response.blob()读取图片并设置 Content-Type

根据实际需求选择合适的 Content-Type 是前后端通信的关键,可以提高数据解析的正确性和系统的兼容性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值