当我尝试使用通过 npm 安装的 request-promise 模块发送 post 请求时,我收到一个错误,但我无法弄清楚原因。
我尝试删除部分选项和标题,但说实话,我只是卡住了。
function sendData() {
var options = {
method: 'POST',
uri: `http://www.myurl.com/placeholder.json`,
body: {
"data":"desiredData"
},
headers: {
"Accept": "application/json",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "en-US,en;q=0.9",
"Connection": "keep-alive",
"Content-Type": "application/x-www-form-urlencoded",
"X-Requested-With": "XMLHttpRequest"
}
}
rp(options)
.then(function (parsedBody) {
console.log(parsedBody)
})
.catch(function (err) {
console.log(err)
});
}
sendData();
应该发送一个 post 请求并记录返回的 json,但我收到以下错误:
_http_outgoing.js:654
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'first argument',
^
TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be one of type string or Buffer
at write_ (_http_outgoing.js:654:11)
at ClientRequest.write (_http_outgoing.js:629:10)
at Request.write (C:\Users\ninja_000\Desktop\TronJS\node_modules\request\request.js:1500:27)
at end (C:\Users\ninja_000\Desktop\TronJS\node_modules\request\request.js:549:18)
at Immediate.<anonymous> (C:\Users\ninja_000\Desktop\TronJS\node_modules\request\request.js:578:7)
at runCallback (timers.js:756:18)
at tryOnImmediate (timers.js:717:5)
at processImmediate [as _immediateCallback] (timers.js:697:5)
最佳答案
我创建了这个示例,以便理解 request-promise
的功能。
将 option.body
设置为您的数据,并设置 json: true
将正文编码为 JSON。
我使用一个简单的在线假 REST API 服务器,因此您可以运行该示例而无需更改任何内容。
const rp = require('request-promise');
function sendData() {
var options = {
method: 'POST',
uri: 'https://jsonplaceholder.typicode.com/posts',
body: {
title: 'foo',
body: 'bar',
userId: 1
},
headers: {
"Content-type": "application/json; charset=UTF-8"
},
json: true // Automatically stringifies the body to JSON
};
rp(options)
.then((parsedBody) => {
console.log(parsedBody);
})
.catch((err) => {
console.log(err);
});
}
sendData();
关于node.js - 发送 POST 请求时 Nodejs 请求 promise 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53962091/