My code is attempting to post data to a Coldfusion API from my local Node.js server. I have managed to communicate with the API and authenticate myself via the request headers. However I am having difficulty actually passing my JSON object through as I cannot get the structure right.
我的代码试图将数据从本地节点发送到Coldfusion API。js服务器。我已经设法与API通信,并通过请求头进行身份验证。但是,由于无法正确地传递JSON对象,所以实际上我有困难。
The API does not accept the JSON option of the request module, so that is my easiest option out of the window.
API不接受请求模块的JSON选项,所以这是我在窗口之外最简单的选项。
The API is expecting the following:
API预期如下:
{
'source': {
'customer': {
'customerlogin': 'myusername',
'customerpassword': 'mypassword',
}
}
}
my code works if I hard code the following body parameter (from a sucessful post by somebody else) into my post.
我的代码是工作的,如果我硬编码下面的身体参数(从一个成功的帖子,其他人)到我的帖子。
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);
});
If I send the JSON through in other ways, for example json.stringify(), it is rejected on the grounds that 'source is required but not defined'.
如果我以其他方式发送JSON,例如json.stringify(),它将被拒绝,理由是“源是必需的,但没有定义”。
So I suppose my question is, in node.js how do I turn JSON into something that looks like this
我的问题是,在node。如何将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'
or have I overlooked another option?
还是我忽略了另一个选择?
Thanks for any help and apologies if I have used incorrect terminology.
如果我使用了不正确的术语,谢谢您的帮助和道歉。
1 个解决方案
#1
4
I think this should work:
我认为这应该行得通:
var querystring = require('querystring');
...
request({
...
headers : { 'Content-Type': 'application/x-www-form-urlencoded', ... },
body : 'source=' + querystring.escape(JSON.stringify({
'customer': {
'customerlogin': 'myusername',
'customerpassword': 'mypassword',
}
})),
...
}, ...)
Your example also contains newlines and carriage returns and such, but I'm assuming those are optional.
您的示例还包含换行符和回车符等,但我假设它们是可选的。
#1
4
I think this should work:
我认为这应该行得通:
var querystring = require('querystring');
...
request({
...
headers : { 'Content-Type': 'application/x-www-form-urlencoded', ... },
body : 'source=' + querystring.escape(JSON.stringify({
'customer': {
'customerlogin': 'myusername',
'customerpassword': 'mypassword',
}
})),
...
}, ...)
Your example also contains newlines and carriage returns and such, but I'm assuming those are optional.
您的示例还包含换行符和回车符等,但我假设它们是可选的。