繁体   English   中英

Axios 不尊重 Content-Type 标头

[英]Axios not respecting Content-Type header

这是我的 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 未传递 Content-Type 标头

未为 safari 设置 Axios Header 的 Content-Type

但是我的服务器允许在 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 具有出色的请求正文处理。

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

那么,为什么在 StackOverflow 上会出现无数关于自定义content-type标头的问题呢? 我什至会争辩说,除非您的 API 使用正确的内容协商,否则您也不需要弄乱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,您显然可以在其中使用

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM