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

相关推荐
devlei5 小时前
从源码泄露看AI Agent未来:深度对比Claude Code原生实现与OpenClaw开源方案
android·前端·后端
Jagger_6 小时前
周末和AI肝了两天,终于知道:为什么要把AI当做实习生
前端
weixin_456164836 小时前
vue3 子组件向父组件传参
前端·vue.js
沉鱼.446 小时前
第十二届题目
java·前端·算法
Setsuna_F_Seiei6 小时前
CocosCreator 游戏开发 - 多维度状态机架构设计与实现
前端·cocos creator·游戏开发
Bigger7 小时前
CodeWalkers:让 AI 助手化身桌面宠物,陪你敲代码的赛博伙伴!
前端·app·ai编程
cyclv8 小时前
无网络地图展示轨迹,地图瓦片下载,绘制管线
前端·javascript
土豆12508 小时前
Tauri 入门与实践:用 Rust 构建你的下一个桌面应用
前端·rust
小陈工9 小时前
2026年4月2日技术资讯洞察:数据库融合革命、端侧AI突破与脑机接口产业化
开发语言·前端·数据库·人工智能·python·安全
IT_陈寒10 小时前
Vue的这个响应式问题,坑了我整整两小时
前端·人工智能·后端