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

相关推荐
我是苏苏2 小时前
Web开发:C#通过ProcessStartInfo动态调用执行Python脚本
java·服务器·前端
无羡仙2 小时前
Vue插槽
前端·vue.js
用户6387994773053 小时前
每组件(Per-Component)与集中式(Centralized)i18n
前端·javascript
SsunmdayKT3 小时前
React + Ts eslint配置
前端
开始学java3 小时前
useEffect 空依赖 + 定时器 = 闭包陷阱?count 永远停在 1 的坑我踩透了
前端
zerosrat3 小时前
从零实现 React Native(2): 跨平台支持
前端·react native
狗哥哥3 小时前
🔥 Vue 3 项目深度优化之旅:从 787KB 到极致性能
前端·vue.js
青莲8433 小时前
RecyclerView 完全指南
android·前端·面试
青莲8433 小时前
Android WebView 混合开发完整指南
android·前端·面试