javascript - 在查询字符串中发布嵌套对象 - Node.js

标签 javascript json node.js post

我的代码正在尝试从我的本地 Node.js 服务器将数据发布到 Coldfusion API。我已经设法与 API 通信并通过请求 header 对自己进行身份验证。但是,由于我无法正确地传递我的 JSON 对象,因此我很难通过它。

API 不接受请求模块的 JSON 选项,所以这是我最简单的选项。

API 需要以下内容:

{ 
    'source': { 
        'customer': {
            'customerlogin': 'myusername',
            'customerpassword': 'mypassword',
         }
     }
}

如果我将以下正文参数(来自其他人的成功帖子)硬编码到我的帖子中,我的代码就可以工作。

var Jrequest = require('request');

var options = {
  uri: 'http://myAPI/customerSSO.json',
  headers: {'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': something', 'Timestamp': timestamp},
  method: 'POST',
  body: 'source=%7B%0D%0A++%22customer%22%3A+%7B%0D%0A++++%22customerlogin%22%3A+%22myusername%22%2C%0D%0A++++%22customerpassword%22%3A+%22mypassword%22%2C%0D%0A%09%22success%22%3A+%22%22%0D%0A++%7D%0D%0A%7D' // Working
};


Jrequest(options, function (error, response, body){
    res.send(body);
});

如果我以其他方式发送 JSON,例如 json.stringify(),它会被拒绝,理由是“需要源但未定义”。

所以我想我的问题是,在 node.js 中,我如何将 JSON 变成这样的东西

'source=%7B%0D%0A++%22customer%22%3A+%7B%0D%0A++++%22customerlogin%22%3A+%22myusername%22%2C%0D%0A++++%22customerpassword%22%3A+%22mypassword%22%2C%0D%0A%09%22success%22%3A+%22%22%0D%0A++%7D%0D%0A%7D'

还是我忽略了另一个选择?

感谢您的帮助,如果我使用了不正确的术语,我们深表歉意。

最佳答案

我认为这应该可行:

var querystring = require('querystring');
...
request({
  ...
  headers : { 'Content-Type': 'application/x-www-form-urlencoded', ... },
  body    : 'source=' + querystring.escape(JSON.stringify({
    'customer': {
      'customerlogin': 'myusername',
      'customerpassword': 'mypassword',
    }
  })),
  ...
}, ...)

您的示例还包含换行符和回车等,但我假设这些是可选的。

关于javascript - 在查询字符串中发布嵌套对象 - Node.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19379208/

相关文章:

php - 错误 : org. json.JSONException : Value <br of type java. lang.String 无法转换为 JSONObject

javascript - 将 javascript 映射传递给 json wcf 服务

javascript - 在 NodeJS 中安排一个异步函数

javascript - 在 expressjs 中创建模型

javascript - 单击第一行的按钮时如何获取下一行的对象详细信息?

javascript - Blockly,检测连接/移除/拖动/释放 block

c# - 如果要删除某些元素,如何迭代 JObject?

javascript - 如何同时调用异步函数并等待所有回调?

javascript - 根据内容使用动态宽度的 Bootstrap 弹出窗口

JavaScript React 在源选项卡中隐藏源文件