Axios采坑之路

Axios采坑之路

POST请求设置Content-Type

由于后端采用的是form表单形式上送参数,需要设置Content-Type

  • axios设置如下
const _axios = axios.create(config);
_axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;';
  • api调用
import { request } from '@plugin/axios'
export const getEventDataList = data => {
  return request ({
    url: '/xxx/initialize',
    method: 'post',
    params: data
  })
}
  • 使用chrome调试工具看

    post请求,参数以query string的形式上送,requestheadersContent-Type参数,试过很多方法都不行

image

后来后端说参数应该在body上送,并且把参数转成query string的形式就可以了

  • 调用方式改为如下方式
import { request } from '@plugin/axios'
import qs from 'qs'

export const getEventDataList = data => {
  return request ({
    url: '/xxx/initialize',
    method: 'post',
    data: qs.stringify(data)
  })
}
  • 使用chrome调试工具看,有Content-Type参数了,并且参数是以Form Data的形式上送,不再是query string

image

  • 总结

post请求只有参数使用body上送设置Content-Type才能生效,post请求参数是以query string的形式上送,则无法设置Content-Type

猜你喜欢

转载自www.cnblogs.com/iPing9/p/10917359.html