【问题记录】axios修改请求数据格式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fifteen718/article/details/82110970

默认请求数据的格式是这样的:

修改请求头信息

headers: {  'Content-Type': 'application/x-www-form-urlencoded'  }

修改请求数据

transformRequest: [function (data, headers) {
    let ret = ''
    for (let it in data) {
        if (data[it] === 0 || (data[it] || data[it] === '') || data[it] === false) {
            if (ret !== '') ret += '&'
            ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it])
        }
    }
    return ret
}]

关于axios的具体代码配置如下:

const instance = axios.create({
    // 设置超时时间
    timeout: 30000,
    // 请求的baseUrl
    baseURL: baseUrl,
    // 请求头部信息
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    // 修改请求数据
    transformRequest: [function (data, headers) {
        let ret = ''
        for (let it in data) {
            if (data[it] === 0 || (data[it] || data[it] === '') || data[it] === false) {
                if (ret !== '') ret += '&'
                ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it])
            }
        }
        return ret
    }],
    // 跨域请求时允许携带凭证(cookie)
    withCredentials: true
})

猜你喜欢

转载自blog.csdn.net/fifteen718/article/details/82110970
今日推荐