【问题标题】:Axios not respecting Content-Type headerAxios 不尊重 Content-Type 标头
【发布时间】:2023-01-26 06:42:35
【问题描述】:

这是我的 axios 配置:

import axios from "axios"

const axiosApi = axios.create({
  baseURL: import.meta.env.VITE_API_URL
})

const requestInterceptor = config => {
  config.headers['Content-Type'] = 'application/json';
  config.headers['Accept'] = 'application/json';
  config.headers['X-Client'] = 'React';
  return config;
}

axiosApi.interceptors.request.use(requestInterceptor);

const get = async (url) => {
  return await
    axiosApi.get(url, {
      crossDomain: true
    }).then(response => {
      return response?.data;
    })
}

const post = async (url, data) => {
  return await axiosApi
    .post(url, Array.isArray(data) ? [...data] : { ...data })
    .then(response => response?.data)
}

const form = async (url, data) => {
  return await axiosApi
    .post(url, data, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
    .then(response => response?.data)
}

如您所见,对于 postget 实用程序方法,我使用了一个设置默认值的请求拦截器。因此我为他们使用Content-Type: application/json

但是,对于form,我将Content-Type 标头覆盖为一个表单。

我读了一些其他问题,包括:

Axios not passing Content-Type header

Axios Header's Content-Type not set for safari

但是我的服务器允许在 CORS 请求中发送 Content-Type

Access-Control-Allow-Headers: authorization,content-type,x-client
Access-Control-Allow-Methods: POST
Access-Control-Allow-Origin: *

但是当我使用form方法时,我看到Content-Type没有设置为application/json,而不是application/x-www-form-urlencoded

我做错了什么?

【问题讨论】:

  • 为什么要搞乱 Axios 默认处理内容类型标头的方式?
  • 混乱?这一切都来自它的文档。我们使用拦截器,它们来自文档。
  • 您不需要 response?.data 中的可选链接。如果请求得到解决,response 保证是一个Axios response 实例

标签: javascript axios


【解决方案1】:

默认情况下,Axios 具有出色的请求正文处理。

  • 如果它看到一个普通的 JavaScript 对象或数组,它会使用 application/json
  • 如果您传入纯字符串或URLSearchParams 的实例,它将使用application/x-www-form-urlencoded
  • 传入一个FormData实例,它将使用multipart/form-data

那么,为什么在 Stack Overflow 上会出现无穷无尽的带有自定义 content-type 标头的问题?我什至会争辩说,除非您的 API 使用正确的 content negotiation,否则您也不需要弄乱 Accept 标头。

我认为您的情况不需要拦截器。只需在您的实例上设置请求标头默认值

axiosApi.defaults.headers.common["X-Client"] = "React";
// and if your API actually uses content negotiation...
// axiosApi.defaults.headers.common.Accept = "application/json";

至于你的url编码请求,Axios 0.x 通过URLSearchParams 或纯字符串支持此请求。它不会自动将普通对象转换为application/x-www-form-urlencoded

如果你的data是一个平面对象,你可以使用下面的

const form = async (url, data) => {
  const encodedData = new URLSearchParams(data);
  return (await axiosApi.post(url, encodedData)).data;
};

如果它更复杂,我建议使用像qs 这样的库。

否则,等待 Axios 1.0,您可以在apparently使用它

axios.post(url, data, {
  headers: { "content-type": "application/x-www-form-urlencoded" }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    • 2017-05-19
    • 2021-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多