5

我正在尝试使用以下代码使 JSONP 响应正常工作...

$http.jsonp('http://example.com:8888/?callback=JSON_CALLBACK').success( function( response )
{
    console.dir( response );
});

http://example.com:8888/?callback=JSON_CALLBACK通过 node.js 返回以下内容

JSON_CALLBACK({ 日期:'2013-05-15T08:53:51.747Z' });

像这样在 node.js 中设置标头....

res.writeHead(200, {'Content-Type': 'application/json'});

然而,我在 Chrome 控制台中遇到的错误是……

Uncaught ReferenceError: JSON_CALLBACK is not defined 

然而,奇怪的是,如果我创建window.JSON_CALLBACK(response)它会运行的函数。但我认为成功是为了代表我做到这一点。

4

4 回答 4

2

您的内容类型标头不正确。

application/json如果您返回的是纯 JSON,请使用。JSONP 是 Javascript,所以你应该使用application/javascript

于 2013-05-15T09:18:25.707 回答
0

Here is a quick and dirty solution. Instead of outputting JSON_CALLBACK({ date:'2013-05-15T08:53:51.747Z' }), you can try to output angular.callbacks._0({ date:'2013-05-15T08:53:51.747Z' }). I believe this is bug in Angular.

An alternative is to request your url this way:

$http({
  method: 'JSONP',
  url: 'https://something.com/' + '?callback=JSON_CALLBACK' + '&otherstuffs'
});

PS. If you use php backend, I noticed changing the name of the php file will sometimes have positive result (like instead of using index.php we can try api.php). Although it seems to be completely random (what name works and vise versa) - I think this has to do with how Angular read the url of the json.

It looks like the reason of this unfortunate bug is that Angular will replace the JSON_CALLBACK to angular.callbacks._0 but it will fail sometimes due to its URL interpreter.

Additionally, even if it succeeded the server you are using may not support the ?callback=angular.callbacks._0 in the url (which is a common behavior among servers).

于 2015-03-06T21:42:46.793 回答
0

请参阅angular $resource with jsonp not working 这个问题已在 git 中打开:https ://github.com/angular/angular.js/issues/1551

于 2013-08-20T10:21:58.067 回答
0

我发现了这个黑客,它对我有用

    //.......................ini: 哈克
    /*
        在您的 $http 请求之前复制粘贴此代码。
    */      
        var c = $window.angular.callbacks.counter.toString(36);

        $window['angularcallbacks_' + c] = 函数(数据){
            $window.angular.callbacks['_' + c](data);
            删除 $window['angularcallbacks_' + c];
        };     
    //......................................结束:黑客

    //你的 $http 请求
    $http.jsonp(网址)
     .成功(函数(){
        控制台日志(“确定”)
    })
     .error(函数(数据,状态,标题,配置){
        console.error("ko");
    });  
于 2014-01-27T17:02:51.253 回答