6

我正在尝试复制下面的 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 的

4

1 回答 1

11

我尝试通过在选项中设置路径来将其附加到路径:/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'
    })
});
于 2013-01-20T04:15:43.640 回答