【问题标题】:How to POST with request in Express如何在 Express 中使用请求发布
【发布时间】:2016-10-18 15:27:17
【问题描述】:

所以我正在尝试使用request 模块将新用户发布到对讲机,但似乎无法正确获取格式。我可以用请求和 POST 用 CURL 的相同数据来做 GET 请求。所以我的结论是我使用请求库的方式一定有问题。

工作 CURL 请求:

    curl https://api.intercom.io/users \
-X POST \
-u xxx:da39xxxxxxxxxxxxxxxxx0709 \
-H 'Accept: application/json' \
-H 'Content-Type: application/json' -d '
{
  "user_id": "25",
  "email": "wash@serenity.io",
  "name": "Hoban Washburne",
  "signed_up_at": 1392731331,
  "last_seen_ip" : "1.2.3.4"
}

服务器端请求无效:

  request.post('https://api.intercom.io/users',
  {
    'auth': {
      'user': 'xxx',
      'pass': 'xxx',
      'sendImmediately': false
    }},
      {
        "user_id": "193",
          "email": "test@test.io",
          "name": "Hoban Washburne",
          "signed_up_at": 1392731331,
          "last_seen_ip" : "1.2.3.4",
      },function (error, response, body) {
    var info = JSON.parse(body);
    console.log(info);
    console.log(error);
  });
res.status(200).send(info);

【问题讨论】:

  • 有什么问题?
  • 您...可能想要撤销该 API 密钥...
  • 这只是文档中的示例 API 密钥。 @slugonamission

标签: node.js express npm http-post httprequest


【解决方案1】:

我根据this blog post更改了请求的格式

这是一个对我有用的答案。

request({
    'url': 'https://api.intercom.io/users', //URL to hit
    'method': 'POST',
    'headers': {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    },
    'auth': {
      'user': 'xxxxxx', //org ID
      'pass': 'xxxxxxxxxxxxx', //API key
      'sendImmediately': false
    },

    //Lets post the following key/values as form
    'json': {
      "user_id": "193",
        "email": "test@test.io",
        "name": "Hoban Washburne",
        "signed_up_at": 1392731331,
        "last_seen_ip" : "1.2.3.4"
    }
}, function(error, response, body){
    if(error) {
        console.log(error);
    } else {
        console.log(response.statusCode, body);
    }
    res.status(200).send("this is a test");
});

【讨论】:

    猜你喜欢
    • 2018-05-04
    • 2014-06-15
    • 1970-01-01
    • 2018-08-25
    • 2017-03-09
    • 1970-01-01
    • 2012-12-13
    • 1970-01-01
    • 2020-08-20
    相关资源
    最近更新 更多