Axios 返回 500 错误而请求返回响应

时间:2021-06-14 12:23:09

标签: javascript axios requestjs

我已使用 javascript 包从我的 requests 代码调用 API。但由于它已被弃用,我想用 axios 替换它。

调用是这样的:

request({
  url: 'the_url',
  method: 'POST',
  encoding: null,
  headers: {
    'Content-Type': 'application/x-protobuf',
    'Connection': 'Keep-Alive',
    'Accept-Encoding': 'gzip',
  },
  body: requestBody,
}, callback);

requestBody 在哪里 Uint8Array 我用我需要发送的数据创建。以上工作正常,我得到了我需要的回应。但是,当我像这样将其重写为 axios

axios({
    url: 'the_url',
    method: 'POST',
    encoding: null,
    headers: {
      'Content-Type': 'application/x-protobuf',       
      'Connection': 'Keep-Alive',
      'Accept-Encoding': 'gzip',
    },
    data: requestBody,
  }
).then( (res) => {
  console.log(res);
}).catch( (error) => {
  console.log(error);
})

服务器返回 500 错误。这是完全相同的网址和相同的 requestBody 变量。

编辑:当我检查两种情况的实际请求对象时,它看起来传递的 requestBody 没有完全相同的格式。

request的情况下,是这样的:

body: <Buffer 22 07 ... ... 396 more bytes>

但是在axios这样的情况下

data: ArrayBuffer {
  [Uint8Contents]: <22 07 ... ... 346 more bytes>,
  byteLength: 446
}

requestBody 的创建没有任何变化。我在两种情况下都传递完全相同的参数。因此,它必须与 axiosrequests 如何处理这些情况有关。

1 个答案:

答案 0 :(得分:0)

试试这个

let formData = new FormData()

formdata.append('reqBody', requestBody)

axios({
    url: 'the_url',
    method: 'POST',
    encoding: null,
    headers: {
      'Content-Type': 'multipart/form-data',       
      'Connection': 'Keep-Alive',
      'Accept-Encoding': 'gzip',
    },
    data: formdata,
  }
).then( (res) => {
  console.log(res);
}).catch( (error) => {
  console.log(error);
})