zoukankan      html  css  js  c++  java
  • axios的get请求无法设置Content-Type

    最近在与后端的项目对接中,接口工具使用了axios这个东西。怎么说那 ,反正有很多坑,在后端的请求中要设置GET 请求中要设置header中的Content-Typeapplication/json; charset=utf-8

    我目视了两秒钟很简单的嘛

    var $http  = axios.create({
      baseURL: url,
      headers: {
        'Content-Type': 'application/json; charset=utf-8'
      }
      ...
    })
    

      

    洒洒水啦 ,是不是很容易

    然后。。然后。。我艹what fuck,一看请求中header中没得这个玩意儿,但是除了Content-Type都是可以设置的

    此时此刻一万句mmp要将,百度一大推也都没啥用

    然后本人就去读了一哈源码,npm包中的源码 axios/lib/xhr.js,写了什么,我艹 他写了什么

    118------129行

        // 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);
            }
          });
        }
    

      

    然后看这个if判段, 哔了狗了

    然后就有那么几个解决办法,下面我写一写哈

    • 方法一
    //修改这段代码
        // 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);
            //}
          });
        }
    

      

    好了,行了行了,现在可以了
    

      

    • 方法二 
      我们不能随随便便改人家的npm包啊,万一下次别人安装的时候那不是又要去改,咋办呢,看下面这个方法 
    var $http
    // 添加一个新的axios实例
    $http = axios.create({
      baseURL: url,
      headers: {
        'Content-Type': 'application/json; charset=utf-8'
      }
    })
    // 添加请求拦截器
    $http.interceptors.request.use(function (config) {
      // 在发送请求之前做些什么
      // 随便写个值 绕过if判段
      if (config.method == 'get') {
        config.data = true
      }
      config.headers['H-TOKEN'] = '111'
      return config;
    }, function (error) {
      // 对请求错误做些什么
      return Promise.reject(error);
    });
    

      

    现在哥哥告诉你,随便在get请求中设置header那还不是简简单单的事情
    

      

    axios这么做的原因, 是因为GET请求本身是不需要Content-type,塔属于简单请求

    原文作者:echone_wenqian

    原文地址:https://blog.csdn.net/qq_24729895/article/details/80367460

  • 相关阅读:
    冒泡排序
    Window中常见的dos命令
    spring boot 重定向
    阿里云轻量级服务器使用
    网络知识
    spring boot security 登出
    深入理解java虚拟机
    jsp内置对象与servlet的关系
    求一个有向无换图中,最长简单路径。动态规划问题15-1
    一些动态规划问题的java实现
  • 原文地址:https://www.cnblogs.com/gxsyj/p/10697593.html
Copyright © 2011-2022 走看看