返回JSONP的Restful api的节点HTTP请求

问题描述 投票:10回答:2

我试图使用node.js对服务器端调用restful API。 使用JSONP(JS函数内的JSON容器)返回的错误似乎是节点http.get(options,callback)API的核心。 节点或任何模块可以从JSONP返回返回JSON对象吗?

示例JSONP请求: http//www.linkedin.com/countserv/count/share? url = http://techcrunch.com/2012/01/29/turning-two-founderscard-pulls-back-the-curtain-在其通会员制社区的创业者/

http node.js jsonp
2个回答
8
投票

使用vm执行回调

JavaScript code can be compiled and run immediately or compiled, saved, and run later

之前的回答建议去掉回调函数。 不幸的是,这与许多jsonp响应不兼容,因为函数的内容通常是对象而不是纯JSON。 JSON.parse()函数将死于以下内容:

callback({key:"value"});

虽然上面是一个有效的对象,但它不是有效的JSON。

以下将执行回调并返回对象:

jsonpSandbox = vm.createContext({callback: function(r){return r;}});
myObject = vm.runInContext(jsonpData,jsonpSandbox);

创建上下文更改时, callback到jsonp响应中返回的回调函数的名称。


6
投票

我编写了一个包装器函数,它检查JSON并从返回的字符串中删除该函数,以避免运行eval。 然后在字符串上的JSON.parse(现在减去自我们删除后的函数)返回json。

var request = require('request');
var getJsonFromJsonP = function (url, callback) {
request(url, function (error, response, body) {
  if (!error && response.statusCode == 200) {
    var jsonpData = body;
    var json;
    //if you don't know for sure that you are getting jsonp, then i'd do something like this
    try
    {
       json = JSON.parse(jsonpData);
    }
    catch(e)
    {
        var startPos = jsonpData.indexOf('({');
        var endPos = jsonpData.indexOf('})');
        var jsonString = jsonpData.substring(startPos+1, endPos+1);
        json = JSON.parse(jsonString);
    }
    callback(null, json);
  } else {
    callback(error);
  }
})
}

然后像这样使用它:

getJsonFromJsonP('http://www.linkedin.com/countserv/count/share?url=http://techcrunch.com/2012/01/29/turning-two-founderscard-pulls-back-the-curtain-on-its-membership-community-for-entrepreneurs/', function (err, data) {
    console.log('data count', data.count);
});
© www.soinside.com 2019 - 2024. All rights reserved.