node.js - NodeJS - ERR_INVALID_ARG_TYPE 向远程主机发出 HTTP 请求时抛出错误
问题描述
最近,我在尝试使用 NodeJS 和request-promise发出请求时遇到了一个问题。
以下代码嵌套在用于文件上传的 multer 调用中(使用嵌套函数/集群。
const options = {
method: 'POST',
uri: 'URL of your choice',
body: {
//Body of the request
},
// json: true,
headers: {
// 'Content-Type': 'application/x-www-form-urlencoded',
},
}
request(options)
.then(function (response) {
console.log('Response: ', response);
})
.catch(function (err) {
console.log('Error: ', err);
});
在使用当前请求时,没有 'json: true' 属性(已注释掉),我收到以下错误:
TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be one of type string or Buffer. Received type object
at write_ (_http_outgoing.js:603:11)
at ClientRequest.write (_http_outgoing.js:575:10)
at Request.write (PATH/node_modules/request/request.js:1500:27)
at end (PATH/node_modules/request/request.js:549:18)
at Immediate.<anonymous> (PATH/node_modules/request/request.js:578:7)
at runCallback (timers.js:696:18)
at tryOnImmediate (timers.js:667:5)
at processImmediate (timers.js:649:5)
at process.topLevelDomainCallback (domain.js:121:23)
当我打开 'json: true' 选项时,问题不会发生,但远程 API 会返回错误,因为它不能很好地处理 JSON 请求/它们添加的花括号。
关于克服这个问题的任何想法?
谢谢你。
解决方案
解决了!
由于远程主机不能很好地处理 JSON,并且需要发送“普通” POST 请求,我再次查看了 request-promise 的文档。通过更改body{}
为formData{}
并注释掉json: true
,问题就解决了。
const options = {
method: 'POST',
uri: 'URL of your choice',
formData: {
//Request's data
},
}
request(options)
.then(function (response) {
console.log('Response: ', response);
})
.catch(function (err) {
console.log('Error: ', err);
});
推荐阅读
- javascript - 谷歌应用脚本查找值然后复制整行
- javascript - 在javascript中以英寸为单位获取屏幕尺寸
- java - 我从注册面板获取空值到我的数据库
- android - Flutter APP 不初始化,尤其是在 Galaxy Note 设备上
- python - 在基于 Windows 的 Apache Aiflow 工作者上执行 Airflow 任务
- python - Python 简单的加密货币程序,没有通过 id 找到某些货币
- azure - Azure Blob 存储追加 Blob 409/在追加时刷新门户/存储资源管理器时出现修改错误
- python - 矩阵转置 python 4x3 到 3x4 python
- java - javax.transaction.Transactional 无法指定隔离级别是什么原因?
- r - 函数 fread 和 ASCII 文件