网站项目中 Ajax 的 Content-Type 详解

451 阅读2分钟

介绍

在使用 AJAX 进行异步 HTTP 请求时,Content-Type 头部指定了请求体中数据的媒体类型。根据您传输的数据格式,常用的 Content-Type 值包括:

  • application/json: 发送 JSON 数据,适用于复杂的结构化数据。

  • application/x-www-form-urlencoded: 用于发送表单数据,默认情况下当使用 HTML 表单提交时采用此格式。

  • multipart/form-data: 用于上传文件和表单数据,允许同时发送二进制数据(如文件)。

  • text/plain: 用于发送纯文本数据。

  • application/xml: 用于发送 XML 数据。 text/html:用于发送 HTML 数据。

最常用的 AJAX 的 Content-Type 值主要包括 application/jsonapplication/x-www-form-urlencodedmultipart/form-data

举例

application/json

前端请求 application/json

axios.post('http://example.com/api/users', {
        username: 'exampleUser',
        password: 'securePassword123'
    })
    .then(response => {
        console.log('Response data:', response.data);
    });

后端接收 application/json

POST /api/users HTTP/1.1
Host: example.com
Content-Type: application/json
Content-Length: 56

{"username":"exampleUser","password":"securePassword123"}

application/x-www-form-urlencoded

前端请求 application/x-www-form-urlencoded

// qs 可以把对象转成 URL 编码的字符串格式
axios.post('http://example.com/api/login', qs.stringify({
    username: 'exampleUser',
        password: 'securePassword123'
    }), {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded' // 设置请求头
        }
    })
    .then(response => {
        console.log('Response data:', response.data);
    });

后端接收 application/x-www-form-urlencoded

POST /api/login HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 55

username=exampleUser&password=securePassword123

multipart/form-data

前端请求 multipart/form-data

const formData = new FormData();
formData.append('username', 'username_value');
formData.append('password', 'password_value');
formData.append('rememberMe', 'true');
formData.append('profilePicture', fileInputDom.files[0]);

axios.post('http://example.com/api/upload', formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    })
    .then(response => {
        console.log('Response data:', response.data);
    });

后端接收 multipart/form-data

POST /api/upload HTTP/1.1
Host: example.com
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="username"

exampleUser
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="password"

securePassword123
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="rememberMe"

true
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="profilePicture"; filename="profile.jpg"
Content-Type: image/jpeg

<binary data for the image file here>
------WebKitFormBoundary7MA4YWxkTrZu0gW--

一个骚操作

  • 开发生涯中,遇到过一个接口,两个地方传参数的情况,前端按要求后实现的代码如下
axios.post('http://example.com/api/xxx?a=1&b=2', {
        c: 3',
        d: 4'
    })
    .then(response => {
        console.log('Response data:', response.data);
    });
  • 服务端收到的请求实际上分两部分,一部分是来自api链接上的查询参数 ab ,另一部分是请求体中的 cd 组成的 json 数据。

  • 服务端如何处理呢?很简单

app.use(bodyParser.json()); // 解析 JSON 格式的请求体

const a = req.query.a; // 获取查询参数 a
const b = req.query.b; // 获取查询参数 b
const c = req.body.c; // 获取请求体中的 c
const d = req.body.d; // 获取请求体中的 d