【问题标题】:Using Parse.com REST API with query in node.js - how to use data-encode from CURL在 node.js 中使用 Parse.com REST API 和查询 - 如何使用来自 CURL 的数据编码
【发布时间】:2013-01-03 11:21:24
【问题描述】:

我正在尝试复制下面的 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 上的一个例子,我实现了这个功能:

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

我的问题是,如何发送 "--data-urlencode 'where={"playerName":"Sean Plott","cheatMode":false}' 位?我尝试通过设置将其附加到路径像这样的选项中的路径:'/1/classes/GameScore?playerName=John,但这不起作用,我收到了所有的 GameScore,而不是 John 的那些

【问题讨论】:

  • 为什么不直接使用官方的 Parse JavaScript SDK?此外,您可以查看其源代码以了解如何使用其余 api。 npmjs.org/package/parse

标签: node.js curl parse-platform


【解决方案1】:

我尝试通过在选项中设置路径来将其附加到路径中:/1/classes/GameScore?playerName=John

似乎期望 where 作为键/名称,其值是整个 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'
    })
});

【讨论】:

  • 这是一个有用的答案。但是我有一个问题,PUT(update) 怎么样?
  • @smartworld-konoha 您可以使用req.write(JSON.stringify({ ... })); 在请求的正文中提供对象,以及适当的Content-Type 请求标头,通过current Parse Server docs。 – 尽管它使用 URL 编码而不是 JSON,但文档中提供了一个示例,用于http.request()
猜你喜欢
  • 2012-12-14
  • 2014-06-19
  • 1970-01-01
  • 1970-01-01
  • 2013-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-19
相关资源
最近更新 更多