返回JSONP的Restful api的节点HTTP请求 [英] Node HTTP request for Restful api's that return JSONP

查看:633
本文介绍了返回JSONP的Restful api的节点HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am attempting to make server side calls to restful API's using node.js. Returns with JSONP (JSON container inside a JS function) are returning errors that seems to be at the heart of the node http.get(options, callback) API. Can node or any module return the JSON object from a JSONP return?

示例JSONP请求:
http://www.linkedin.com/countserv/count/share?url=http://techcrunch.com/2012/01/29/turning-two-founderscard-pulls-back-the-curtain-on-其成员 - 社区为企业家/

Example JSONP request: 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/

推荐答案

vm

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

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

A previous answer suggests striping the callback function. Unfortunately, this is not compatible with many jsonp responses since the contents of the function are usually objects and not pure JSON. The JSON.parse() function will die for something like the following:

callback({key:"value"});

虽然以上是有效对象,但它不是有效的JSON。

While the above is a valid object, it is not valid JSON.

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

The following will execute the callback and return the object:

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

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

When creating the context change callback to the name of the callback function that is returned in the jsonp response.

这篇关于返回JSONP的Restful api的节点HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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