在查询字符串中发布嵌套对象-Node.js [英] Post nested objects in query string - Node.js

查看:82
本文介绍了在查询字符串中发布嵌套对象-Node.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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期望满足以下条件:

The API is expecting the following:

{ 
    '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);
});

如果我通过其他方式(例如json.stringify())发送JSON,则将其拒绝,理由是需要但未定义源".

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'.

所以我想我的问题是,在node.js中,如何将JSON转换为类似这样的内容

So I suppose my question is, in node.js how do I turn JSON into something that looks like this

'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.

推荐答案

我认为这应该有效:

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.

这篇关于在查询字符串中发布嵌套对象-Node.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆