【发布时间】: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);
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 错误。它是完全相同的 URL 和相同的 requestBody 变量。
编辑:当我检查这两种情况的实际请求对象时,它看起来传递的 requestBody 没有完全相同的格式。
request的情况是这样的:
body: <Buffer 22 07 ... ... 396 more bytes>
但是在axios这样的情况下
data: ArrayBuffer {
[Uint8Contents]: <22 07 ... ... 346 more bytes>,
byteLength: 446
}
requestBody 的创建没有任何变化。在这两种情况下,我都传递了完全相同的参数。因此,它必须与axios 和requests 如何处理这些情况有关。
【问题讨论】:
-
requestBody中有什么内容?它是一个对象,还是一个 JSON 字符串/字符串化对象? -
是一个protobuf,序列化对象,格式为
Uint8Array
标签: javascript axios requestjs