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

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

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,查看源码:

    // Remove Content-Type if data is undefined
    requestData === undefined && requestHeaders.setContentType(null);

如果data未定义则会将Content-Type设置为null;
那么修改data,也是从网上查到的:

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,再次查看源码:

    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:

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:
企业微信截图_20231226180356.png
只能说axios封装了太多东西,官网又很简略。

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值