node.js - 发送 POST 请求时 Nodejs 请求 promise 错误?

标签 node.js request

当我尝试使用通过 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/

相关文章:

request - 重试请求 onErrorResponse Android Volley

Python:使用request从网页获取自动建议的结果

javascript - 在 Node js 中使用来自本地 apache 服务器的 http.request 提取数据失败

javascript - 如何分别获取 CSV 标题和行 Typescript

javascript - 在生产模式下访问 Feathers 客户端插件中的 nuxt.js 环境变量

node.js - Google Actions 是否可以将 CameraStream 与 Dialogflow 实现一起使用?

python - Content-Type in 用于 python 请求中的单个文件

javascript - 字符串原型(prototype)在浏览器中有效,但在 Node 中无效

javascript - 无法获取 Node v5.X 中全局安装的 Node.js 模块的列表

request - 在 ELM 中,GET 请求不能有正文,是吗?