【问题标题】:Does Axios handle the conversion of the response body to responseType in client or does the server handle it?Axios 是在客户端处理响应体到 responseType 的转换,还是由服务器处理?
【发布时间】:2021-07-28 07:52:39
【问题描述】:

我一直在阅读有关HTTP 标头和Accept 的信息,从我阅读的内容来看,它是后端服务器用来了解请求客户端期望什么样的响应的标头。我很好奇它与 Axios 请求的 responseType 选项有什么样的关系,或者根本没有关系。

// `responseType` indicates the type of data that the server will respond with
// options are: 'arraybuffer', 'document', 'json', 'text', 'stream'

假设我向某个 API 发送了一个 GET 请求,我知道该 API 会以 JSON 正文进行响应 我将responseType 设置为arraybuffer,Axios 是否处理该转换?

axios
  .get("https://jsonplaceholder.typicode.com/todos/1", {
    headers: { Accept: "application/json" },
    responseType: "arraybuffer",
  })
  .then((res) => {
    console.log(res.data);
  })
  .catch((err) => {
    console.log(err);
  });

【问题讨论】:

    标签: javascript http axios


    【解决方案1】:

    通过查看代码,responseType 只是决定如何解析(或不解析)响应正文,它与任何标头无关。

    实际的响应类型由Content-Type response header 表示。 Accept request header 应由服务器评估,以根据客户端的偏好从多种内容类型中选择资源(如果可用!)。详情请见content negotiation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-11
      • 1970-01-01
      • 2011-01-03
      • 2018-07-28
      • 1970-01-01
      • 1970-01-01
      • 2011-03-05
      • 2023-01-26
      相关资源
      最近更新 更多