使用Parse.com REST API和node.js中的查询 – 如何使用CURL中的数据编码

我正在尝试复制下面的parse.com rest API的示例:

curl -X GET \ -H "X-Parse-Application-Id: APP_ID" \ -H "X-Parse-REST-API-Key: API_KEY" \ -G \ --data-urlencode 'where={"playerName":"John"}' \ https://api.parse.com/1/classes/GameScore 

所以,基于在Stackoverflow上find的一个例子,我实现了这个function:

 var https = require("https"); exports.getJSON = function(options, onResult){ var prot = options.port == 443 ? https : http; var req = prot.request(options, function(res){ var output = ''; res.setEncoding('utf8'); res.on('data', function (chunk) { output += chunk; }); res.on('end', function() { var obj = JSON.parse(output); onResult(res.statusCode, obj); }); }); req.on('error', function(err) { }); req.end(); }; 

我这样称呼:

 var options = { host: 'api.parse.com', port: 443, path: '/1/classes/GameScore', method: 'GET', headers: { 'X-Parse-Application-Id': 'APP_ID', 'X-Parse-REST-API-Key': 'APP_KEY' } }; rest.getJSON(options, function(statusCode, result) { // I could work with the result html/json here. I could also just return it //console.log("onResult: (" + statusCode + ")" + JSON.stringify(result)); res.statusCode = statusCode; res.send(result); }); 

我的问题是,如何发送“ – 数据urlencode”在哪里= {“playerName”:“肖恩Plott”,“cheatMode”:false}'位?我尝试追加到path通过设置这样的选项:'/ 1 / classes / GameScore?playerName = John,但是这并不奏效,我收到了所有的GameScore,而不是来自John

我尝试通过在选项中设置path来追加到path: /1/classes/GameScore?playerName=John

它似乎在期待作为整个JSON值的键/名称的值:

 /1/classes/GameScore?where=%7B%22playerName%22%3A%22John%22%7D 

你可以用querystring.stringify()得到这个:

 var qs = require('querystring'); var query = qs.stringify({ where: '{"playerName":"John"}' }); var options = { // ... path: '/1/classes/GameScore?' + query, // ... }; // ... 

可以使用JSON.stringify()来格式化来自对象的值:

 var query = qs.stringify({ where: JSON.stringify({ playerName: 'John' }) });