JSON_CALLBACK not found using JSONP

I am trying to get a JSONP response using the following code ...

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

http://example.com:8888/?callback=JSON_CALLBACK returns the following via node.js

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

The header is set in node.js like this ....

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

But the error I get in the Chrome console is ...

 Uncaught ReferenceError: JSON_CALLBACK is not defined 

However, it is strange if I create the window.JSON_CALLBACK(response) function, it will be launched. But I thought that success should do it on my behalf.

+6
source share
4 answers

Invalid title for your content.

Use application/json if you come back, just JSON. JSONP is Javascript, so you should use application/javascript

+2
source

I found this hack and it works for me

  //.........................ini: Hack
     / *
         Copy-Paste this code just before your $ http request.
     * /      
         var c = $ window.angular.callbacks.counter.toString (36);

         $ window ['angularcallbacks_' + c] = function (data) {
             $ window.angular.callbacks ['_' + c] (data);
             delete $ window ['angularcallbacks_' + c];
         };     
     //.........................end: Hack

     // Your $ http request
     $ http.jsonp (url)
      .success (function () {
         console.log ("ok")
     })
      .error (function (data, status, headers, config) {
         console.error ("ko");
     });  
0
source

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

An alternative is to request your URL as follows:

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

PS. If you use php backend, I noticed that changing the php file name sometimes has a positive result (for example, instead of using index.php we can try api.php). Although this seems completely random (which name works and vice versa) - I think this is due to the way Angular reads the json url.

It seems that the reason for this unsuccessful error is because Angular will replace JSON_CALLBACK with angular.callbacks._0 , but sometimes this can happen due to its URL interpreter.

Also, even if it ?callback=angular.callbacks._0 , the server you are using may not support ?callback=angular.callbacks._0 in the URL (which is common among servers).

0
source

Source: https://habr.com/ru/post/945057/


All Articles