axios get方法请求接口设置了headers[‘Content-Type‘]不起作用的问题

在axios封装请求时遇到问题,设置的Content-Type请求头被删除。原因是源码中若requestData未定义,则会移除Content-Type。解决方法包括注释掉删除Content-Type的判断或给requestData赋值。通过修改interceptors.request使用示例展示了如何避免这个问题。
摘要由CSDN通过智能技术生成

遇见问题:在axios封装请求方法中设置了请求头,request headers中没有出现

service.interceptors.request.use(
    config => {
        config.data = JSON.stringify(config.data);
        config.headers['Authorization'] = getToken();
        config.headers['Content-Type'] = "application/json;charset=utf-8";
        
        return config;
    },
    error => {
        return Promise.reject();
    }
);

问题原因:npm下axios的源码中,当未设置requestData的时候会删掉Content-Type的设置

// Add headers to the request
if ('setRequestHeader' in request) {
    utils.forEach(requestHeaders, function setRequestHeader(val, key) {
    if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
      // Remove Content-Type if data is undefined
      delete requestHeaders[key];
    } else {
      // Otherwise add header to the request
      request.setRequestHeader(key, val);
    }
  });
}

解决方法:

1.注释掉源码中  if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') 的判断

2.给requestData赋值 config.data = true

service.interceptors.request.use(
    config => {
        config.data = JSON.stringify(config.data);
        config.headers['Authorization'] = getToken();

        config.data = true
        config.headers[ 'Content-Type'] = "application/json;charset=utf-8";

        return config;
    },
    error => {
        return Promise.reject();
    }
);

 

参考资料:https://blog.csdn.net/qq_24729895/article/details/80367460

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值