关于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封装了太多东西,官网又很简略。

相关推荐
2501_928996226 分钟前
GPT-4o换DeepSeek迁移成本多少?中科热备解析API聚合平台技术账本
前端·数据库·人工智能
东风破_7 分钟前
从跨域到 WebSocket:前端跨域方案、SSE 与双向实时通信详解
前端·后端
原则猫16 分钟前
TS 类型工具
前端
excel1 小时前
Nuxt + Twin CSS 中宽度超过屏幕时底部出现空白的原因与解决方案
前端·javascript
计算机魔术师2 小时前
美国司法部正式站队 OpenAI,AI 训练的版权账要这么算了
前端
IT_陈寒3 小时前
React Hooks闭包陷阱差点让我加班到凌晨
前端·人工智能·后端
风骏时光牛马3 小时前
疑难Bug根因定位与问题复盘分析
前端
创新技术阁3 小时前
FastapiAdmin 系统日志体系与核心配置参数详解
前端·后端·fastapi
掘金酱3 小时前
【社区公告】签到与矿石奖励解耦说明
前端
promiseThen3 小时前
LWC Workflow:用 7 个 Cursor Skill 搭一条 AI 协作开发流水线
前端·ai编程