简体   繁体   English

NPM模块(节点/浏览器)中的JSONP跨域

[英]JSONP in NPM module (Node/Browser) Cross domain

I'm writing an NPM module supposed to work both in Node and on the browser (packed via Browserify). 我正在编写一个NPM模块,该模块应该在Node和浏览器中都能工作(通过Browserify打包)。

Part of its functionality is to execute a JSONP call, and to return the parsed data. 其功能的一部分是执行JSONP调用,并返回已解析的数据。 I can't get it to work. 我无法正常工作。 I tried using the jsonp-client and jsonp npm modules, to little avail. 我尝试使用jsonp-clientjsonp npm模块,但收效甚微。

node-jsonp : https://www.npmjs.com/package/node-jsonp node-jsonphttps : //www.npmjs.com/package/node-jsonp

promise = new promise (resolve, reject) ->

        nodejsonp url, (json) ->
            resolve json

The snippet above works fine in Node, but in the browser fails because of the Same Origin cross domain security policy. 上面的代码段在Node中工作正常,但是在浏览器中由于Same Origin跨域安全策略而失败。

jsonp-client https://www.npmjs.com/package/jsonp-client jsonp-client https://www.npmjs.com/package/jsonp-client

promise = new promise (resolve, reject) ->
        jsonpclient url, (err, data) ->
            if (err)
                console.log err
            resolve data

In this case I get the error "Error: Could not find callback on URL(…)", but I can't understand from the documentation how to properly implement the functionality. 在这种情况下,我会收到错误消息“错误:无法在URL(...)上找到回调”,但是我无法从文档中了解如何正确实现该功能。

Little help? 没有什么帮助? :) :)

Edit: The first package mentioned is actually "node-jsonp" and not "jsonp" 编辑:提到的第一个包实际上是“ node-jsonp”,而不是“ jsonp”

Looks like you use their API incorrect. 看起来您使用的API错误。 Api for first one package is: jsonp(url, opts, fn) , so you should rewrite your code and add opts: 第一个软件包的Api是: jsonp(url, opts, fn) ,因此您应该重写代码并添加opts:

promise = new promise (resolve, reject) ->
    jsonp url, {}, (json) ->
        resolve json

Second one have this in documentation: 第二个在文档中有这个:

On the browser you must supply a valid callback on the URL. 在浏览器上,您必须在URL上提供有效的回调。

It requires manual adding of callback parameter to URL. 它需要手动将回调参数添加到URL。 You should check how jsonp works : it adds callback GET parameter and response wrapped in calling of this callback function. 您应该检查jsonp的工作原理 :它添加了callback GET参数和包装在此回调函数的调用中的响应。 Ie

  • you are sendind request: <api url>?callback=cb ; 您是sendind请求: <api url>?callback=cb ;
  • server renders javascript response, that will be eval -ed in your application cb({json}); 服务器呈现javascript响应,将在您的应用程序cb({json});进行eval cb({json});
  • for handling of this response you should have global function cb , that will receive json as argument. 为了处理此响应,您应该具有全局函数cb ,它将接收json作为参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM