axios添加自定义headers时异常问题

#main.js中axios引入及定义

import axios from 'axios'
axios.defaults.baseURL = 'https://localhost:5001/api/'
Vue.prototype.$http = axios

#get请求调用

##请求参数中未添加data

###调用代码

async getData() {
      var endCreatedDate = new Date()
      var startCreatedDate = new Date()
      startCreatedDate.setDate(startCreatedDate.getDate() - 2)
      var res = await this.$http.get('/Crosstest', {
        params: {
          BarTestingStatus: 'TESTING_BAR_STATUS_HANDOVER',
          BarStartCreatedTime: this.$formatDate('yyyy-MM-dd hh:mm:ss', startCreatedDate),
          BarEndCreatedTime: this.$formatDate('yyyy-MM-dd hh:mm:ss', endCreatedDate)
        },
        headers: {
          'Content-type': 'application/trolleyRFIDData+json'
        }
      })
      console.log(res)
    }

###打印出来的数据

" class="reference-link">axios添加自定义headers时异常问题

此时可看到headers里面并没有自定义字段“Content-type”,然后data是undefined。

##请求参数中添加data

###调用代码

async getData() {
      var endCreatedDate = new Date()
      var startCreatedDate = new Date()
      startCreatedDate.setDate(startCreatedDate.getDate() - 2)
      var res = await this.$http.get('/Crosstest', {
        params: {
          BarTestingStatus: 'TESTING_BAR_STATUS_HANDOVER',
          BarStartCreatedTime: this.$formatDate('yyyy-MM-dd hh:mm:ss', startCreatedDate),
          BarEndCreatedTime: this.$formatDate('yyyy-MM-dd hh:mm:ss', endCreatedDate)
        },
        headers: {
          'Content-type': 'application/trolleyRFIDData+json'
        },
        data: null
      })
      console.log(res)
    }

###打印出来的数据

axios添加自定义headers时异常问题


此时可看到headers里面已包含自定义字段“Content-type”

axios版本是 0.26.1

查询各种资料也没有发现存在这样的问题,先做记录,后续再跟进。

2022-6-29 20:30:55–对于axios来说’Content-Type’是特殊字段?当将中间的’-‘去掉时就可正常添加到请求头了

headers: {
          // eslint-disable-next-line quote-props
          'ContentType': 'application/trolleyRFIDData+json'
        }

axios添加自定义headers时异常问题

讨论数量: 3

感谢回复,一开始就是用postman测试接口直接修改content-type发送也没有报错,然后检查了后端代码怎么都没发现异常才又想到前端的,可以看一下我更新后的内容,从测试结果来看,对于axios来说应该是特殊字符才会有这种结果吧。

1年前 评论
zhaojjiang 6个月前

Github 上找到了一个类似的问题:Setting header: ‘Content-Type’: ‘application/json’ is not working, axios/axios:issue#86

里面也有提到手动传一个空的请求体,即 data: nulldata: {}

按 issue 里说的,你的操作是对的,因为当没有 data 的时候,axios 会移除 content-type

1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!