我的代码正在尝试从我的本地 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/