【问题标题】:Axios returns 500 error while request returns the response请求返回响应时axios返回500错误
【发布时间】:2021-06-14 21:16:23
【问题描述】:

我已经使用requests 包从我的javascript 代码中调用了一个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);

requestBodyUint8Array 我使用需要发送的数据创建的。以上工作正常,我得到了我需要的响应。但是,当我像这样将其重写为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 错误。它是完全相同的 URL 和相同的 requestBody 变量。

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

request的情况是这样的:

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

但是在axios这样的情况下

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

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

【问题讨论】:

  • requestBody 中有什么内容?它是一个对象,还是一个 JSON 字符串/字符串化对象?
  • 是一个protobuf,序列化对象,格式为Uint8Array

标签: javascript axios requestjs


【解决方案1】:

试试这个

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);
})

【讨论】:

  • 得到这个UnhandledPromiseRejectionWarning: TypeError: source.on is not a function,当 FormData 不是一个对象时,Google 说你得到这个:(
猜你喜欢
  • 2020-08-09
  • 2021-05-21
  • 1970-01-01
  • 2019-10-18
  • 1970-01-01
  • 1970-01-01
  • 2020-07-07
  • 1970-01-01
  • 2017-02-17
相关资源
最近更新 更多