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

Lon*_*hot 12 javascript post json node.js

我的代码试图从我的本地Node.js服务器将数据发布到Coldfusion API.我已设法与API通信并通过请求标头对自己进行身份验证.但是我实际上很难通过我的JSON对象,因为我无法正确地获得结构.

API不接受请求模块的JSON选项,因此这是我最简单的选项.

API期望以下内容:

{ 
    'source': { 
        'customer': {
            'customerlogin': 'myusername',
            'customerpassword': 'mypassword',
         }
     }
}
Run Code Online (Sandbox Code Playgroud)

我的代码工作,如果我硬编码下面的身体参数(从其他人的成功的帖子)到我的帖子.

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);
});
Run Code Online (Sandbox Code Playgroud)

如果我以其他方式发送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'
Run Code Online (Sandbox Code Playgroud)

或者我忽略了另一种选择?

如果我使用了错误的术语,感谢您的帮助和道歉.

rob*_*lep 7

我认为这应该有效:

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

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

  • 另一种选择是使用 `encodeURIComponent` 代替 `querystring` 模块.. 不确定是否有优点或缺点 - 可能只是等效的。啊,只是 .toStringed 查询字符串方法并得到了 `function (str) { return encodeURIComponent(str); }` - 没有区别:) (3认同)