前端发送请求之参数处理—【text/plain】与【application/json】

作者 : admin 本文共714个字,预计阅读时间需要2分钟 发布时间: 2024-06-17 共1人阅读

Content-Type就是指 HTTP 发送信息至服务器时的内容编码类型,服务器根据编码类型使用特定的解析方式,获取数据流中的数据。

其实前后端发送请求的方式有 text/plainapplication/json、application/x-www-form-urlencoded、
multipart/form-data等,这版接上一篇,继续介绍【text/plain】与【application/json】。

2、text/plain

设置headers后,直接发送请求

return request({
    path: `/apis/list`,
    // options为object,如{a: 3, b: 4}
    params: options,
    headers: {
        'Content-Type': 'text/plain'
    },
    method: 'POST',
  });

前端发送请求之参数处理—【text/plain】与【application/json】插图 

浏览器里面可以看到请求头:

前端发送请求之参数处理—【text/plain】与【application/json】插图(1)

2、application/json

设置headers后,直接发送请求

return request({
    path: `/apis/list`,
    // options为object,如{a: 3, b: 4}
    params: options,
    headers: {
        'Content-Type': 'application/json'
    },
    method: 'POST',
  });

底层接收params的位置,发送axios请求时,将params,转成字符串发送,如下:

return instance.request({
        method,
        url,
        data: method === 'post' ? JSON.stringify(params) : undefined,
        headers
    });

前端发送请求之参数处理—【text/plain】与【application/json】插图(2)

即可。

以上仅为记录开发时的日志,代码并不完善~

本站无任何商业行为
个人在线分享 » 前端发送请求之参数处理—【text/plain】与【application/json】
E-->