【问题标题】:Sending URL encoded string in POST request using node.js使用 node.js 在 POST 请求中发送 URL 编码字符串
【发布时间】:2017-07-22 18:59:43
【问题描述】:

我在向 Stormpath /oauth/token API 端点发送 url 编码字符串时遇到了困难。该字符串应如下所示:

 grant_type=password&username=<username>&password=<password>

使用 Postman,我通过选择 raw / text 选项在请求正文中提供类似于上述字符串的字符串,成功地访问了端点并检索了我想要的数据。但是当我生成代码 sn-p 时,它看起来像这样:

var request = require("request");

var options = { method: 'POST',
  url: 'https://<My DNS label>.apps.stormpath.io/oauth/token',
  headers: 
   { 'postman-token': '<token>',
     'cache-control': 'no-cache',
     'content-type': 'application/x-www-form-urlencoded',
     host: '<My DNS label>.apps.stormpath.io',
     accept: 'application/json' },
  form: false };

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  console.log(body);
});

那个字符串去哪儿了?我需要一些帮助来理解知道我使用 Postman 将 url 编码的字符串发送到 API 端点与在 Postman 生成的代码中看不到它之间的脱节。因为现在我不知道如何在我的实际应用中重现对端点的成功调用。

对我来说,我似乎应该简单地为请求提供一个body,但结果却是{"error":"invalid_request","message":"invalid_request"}。我也尝试将 url 编码的字符串附加到 url 但返回 404 错误。

我刚刚重新开始使用 API,但在这方面的经验并不丰富。

【问题讨论】:

  • 这看起来像一个查询字符串/查询参数。如果是这种情况,只需将该字符串附加到 url 之后的 ?,如下所示:http://example.com/page?key1=value&amp;key2=value
  • 这似乎是一个 Postman 错误。我会尝试通过Postman App Support README 中提到的途径之一询问/报告它。
  • @qxz 我尝试将格式正确的字符串附加到 url 值,这会返回 404 错误。但是很好看,在我问这个问题之前我确实尝试过。 @Jordan 我会检查一下,谢谢。

标签: node.js api postman stormpath


【解决方案1】:

表单数据需要作为对象发布,这里是一个例子:

request.post('http://service.com/upload', {form:{key:'value'}})

摘自本文档:

https://github.com/request/request#forms

希望这会有所帮助!

【讨论】:

  • 看到这对我来说是最有意义的,但是你可以看到邮递员代码 sn-p 没有任何形式的 url 编码字符串,很奇怪吧?
  • 感谢@robertjd 的帮助。事实证明,我一开始并没有发送一个格式正确的字符串,这就是错误的来源。
猜你喜欢
  • 2015-05-26
  • 2017-05-03
  • 2015-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-28
  • 1970-01-01
  • 2014-07-19
相关资源
最近更新 更多