关于Axios发送Get请求无法添加Content-Type

在拦截器中尝试给headers添加Content-Type:

javascript 复制代码
request.interceptors.request.use(
    config => {
        if (!config.headers['Content-Type']) {
            config.headers['Content-Type'] = 'application/json';
        }
        return config;
    },
    error => {
        return Promise.reject(error)
    }
)

如果是GET请求,会发现请求头中无论如何加不上Content-Type,查看源码:

javascript 复制代码
    // Remove Content-Type if data is undefined
    requestData === undefined && requestHeaders.setContentType(null);

如果data未定义则会将Content-Type设置为null;

那么修改data,也是从网上查到的:

javascript 复制代码
request.interceptors.request.use(
    config => {
        if (config.method === 'get' && !config.data) {
            config.data = {unused: 0};
        }
        if (!config.headers['Content-Type']) {
            config.headers['Content-Type'] = 'application/json';
        }
        return config;
    },
    error => {
        return Promise.reject(error)
    }
)

普通GET请求可以正常添加Content-Type,但是如果需要将Content-Type改成"multipart/form-data",会发现Content-Type变成了false,再次查看源码:

javascript 复制代码
    if (utils.isFormData(requestData)) {
      if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {
        requestHeaders.setContentType(false); // Let the browser set it
      } else if ((contentType = requestHeaders.getContentType()) !== false) {
        // fix semicolon duplication issue for ReactNative FormData implementation
        const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : [];
        requestHeaders.setContentType([type || 'multipart/form-data', ...tokens].join('; '));
      }
    }

就是说如果是一个对象,axios会将Content-Type设为false,意图让浏览器自动设置;

这时修改data:

javascript 复制代码
request.interceptors.request.use(
    config => {
        if (config.method === 'get' && !config.data) {
            // 这个是关键点,加入这行就可以了  解决get  请求添加不上content_type
            //如果设置为对象,axios会强制将content-type=multipart/form-data设置为false
            config.data = true
        }
        if (!config.headers['Content-Type']) {
            config.headers['Content-Type'] = 'application/json';
        }
        return config;
    },
    error => {
        return Promise.reject(error)
    }
)

此时才能正常添加content-type:

只能说axios封装了太多东西,官网又很简略。

相关推荐
Mh18 小时前
基于踩过的坑,浅聊一下vh、svh、lvh、dvh
前端·css·设计模式
刘小灰18 小时前
返璞归真,我开始更新博客了
前端·后端
圆心角20 小时前
Agent 上下文原理:为什么“记住”比“推理”更难
前端·面试·agent
杜子不疼.1 天前
从 Apache HTTP Server 到 CivetWeb:在鸿蒙 PC 的 3.1 MiB HAP 里嵌入 Web 服务器
前端·apache·harmonyos
kyriewen1 天前
AI 生成率进了 KPI,最慌的是写代码最快的人
前端·javascript·程序员
SoaringHeart1 天前
Flutter组件封装:聊天气包图片组件NChatBubble
前端·flutter
狗头大军之江苏分军1 天前
三个月的电商心得
前端·后端
勤恳的马龙1 天前
给 1088 个工具页批量注入 FAQ 和结构化数据:一次幂等的 SEO 工程
前端·javascript
htzyl2061 天前
javaScript中,让你全面了解动态import()的四个真实用途,及与静态import的区别
前端·javascript
钉先生贾1 天前
HarmonyOS 7.0 性能排障实战 43:图片与大资源加载抖动时,怎样区分解码、布局与状态更新
java·前端·harmonyos