axios 中的“Content-Type”和“Content-Encoding”标头

问题描述 投票:0回答:3

我正在使用 [电子邮件受保护],我想验证响应标头。 我无法验证 GET 响应中的标头“Content-Type”和“Content-Encoding”。

  1. “Content-Type”:无论我在请求中传递什么内容类型,响应中的内容类型始终是应用程序/JSON。 示例代码片段:
if (<token is present>) {
   request.headers = {
     authorization : 'Bearer ${token}'
   }
} else {
  config.auth =  {}
}
config.headers = Object.assign(config.header, {
                                'content-type': application/<custom content>,
                                'accept-encoding': 'gzip, deflate, br'
                              }
await axios.get(endPoint, config)
  .then(response => {
           return response
     }*

当我检查response.header时,我看到内容类型显示为“application/json”而不是自定义类型。但是当我在 POSTMAN 中点击相同的 url 时,我可以看到内容类型符合预期。

  1. Content-Encoding:我想验证响应中的内容编码,但我了解到 axios 不会在响应中返回内容编码标头,当我检查他们的 github 时,他们要求使用 axios.interceptors 。我尝试使用拦截器,但仍然没有看到响应的标头。但是当我在 POSTMAN 中尝试时,此标头会作为响应出现。有一些解决方案说需要在服务器端启用 CORS。我从 QA 的角度严格要求它,因为我们无法在服务器端启用 CORS。

任何帮助都非常值得赞赏。

axios
3个回答
1
投票

尝试:

axios.post(your-url, {
    headers: {
       'Content-Encoding': 'gzip'
    }
})

axios.post(your-url, {
    headers: {
        'Accept-Encoding': 'gzip',
    }
})

0
投票

这是设计使然:https://axios-http.com/docs/req_config

我也遇到了这个问题,找不到解决办法。最终使用节点获取代替。


0
投票
  1. Content-Type
    表示触发的请求/响应主体的数据类型,在GET请求中设置
    Content-Type
    是没有意义的,因为没有请求主体。 如果您想获得
    X
    Content-Type 作为响应,您应该在请求中设置
    Accept
    标头,即
    Accept: X
    ,假设您的服务器符合相关的 HTTP 规范。

  2. 您需要在请求中设置

    Accept-Encoding
    ,因为
    Content-Encoding
    通常仅在响应被压缩时才设置。大多数 http 服务器会在请求中检查
    Accept-Encoding
    ,以了解它们是否可以发送压缩响应。

© www.soinside.com 2019 - 2024. All rights reserved.