axios使用transformRequest函数后post异常

  根据设计前端在登录成功后会得到一个token,在每次发起请求的时候都需要在请求header带上这个token,通过axios的transformData数组可以实现这个功能。设置这个数组中的函数后,所有请求的header头里面都能带上token,但所有post请求都返回异常了,后端返回json解析失败,Chrome中查看请求发现post请求的request的payload竟然写的[Object Object]

  原来axios对transformRequest数组中函数的返回值有要求,必须是字符串、FormData或其他Buffer,如果返回的是个自己写的object,不识别当然就被处理成[Object Object]了。axios的GitHub上对于该函数的注释如下:

// `transformRequest` allows changes to the request data before it is sent to the server
  // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'
  // The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
  // FormData or Stream
  // You may modify the headers object.
  transformRequest: [function (data, headers) {
    // Do whatever you want to transform the data

    return data;
  }],

解决办法:transformRequest数组函数中返回data前先进行字符串转换。

transformRequest: [
        (data, headers) => {
            //处理header token
            headers['Authority'] = 'token xxxx'

            return JSON.stringify(data)
        }
    ]

顺便提一句,如果你只是写了transformRequest[],没有定义具体的函数,发送的请求又是json的,一样会出现上面的问题,把这个transformRequest注释掉就好了。

原文地址:https://www.cnblogs.com/wurijie/p/12460944.html