Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
341 views
in Technique[技术] by (71.8m points)

javascript - Not a Legal JSONP API -- How to get data without CALLBACK parameter

Angular 1.6 - JSONP throws EXCEPTION despite Response with status: 200 Ok for URL

Im trying to grab some data from a JSONP endpoint. It looks like the data is being returned in the response but Angular nonetheless throws an error.

var url = "https://careers.icims.com/jobs-api/"

var trustedUrl = $sce.trustAsResourceUrl(url);

$http.jsonp(trustedUrl, {jsonpCallbackParam: 'jobs'}).then(function(res){

    console.log(res); // this is never executed :.(

});

I am getting the following error: Uncaught ReferenceError: jobs is not defined at jobs-api?jobs=angular.callbacks._0:1 where jobs refers to my JSONP prefix

Yet the response returns the JSONP script: enter image description here

Why is this exception being thrown and how can it be cleared? I am on Angular 1.6.0

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Not a Legal JSONP API

The API at that URL is not a legal JSONP API.

It can be gotten with a dangerous service:

app.service("dangerousAPI", function($q) {
  this.get = get;
  
  function get(funcName, url) {
    var dataDefer = $q.defer();
  
    window[funcName] = function(x) {
      dataDefer.resolve(x);
    }

    var tag = document.createElement("script");
    tag.src = url;

    document.getElementsByTagName("head")[0].appendChild(tag);
    
    return dataDefer.promise;
  }
})

Use at your own risk.

The DEMO

angular.module("app",[])
.service("dangerousAPI", function($q) {
  this.get = get;
  
  function get(funcName, url) {
    var dataDefer = $q.defer();
  
    window[funcName] = function(x) {
      dataDefer.resolve(x);
    }

    var tag = document.createElement("script");
    tag.src = url;

    document.getElementsByTagName("head")[0].appendChild(tag);
    
    return dataDefer.promise;
  }
})

.run(function($rootScope, dangerousAPI) {
    var url = "https://careers.icims.com/jobs-api/";
    dangerousAPI.get('jobs',url).then(function(data) {
      $rootScope.data = data;
    })
})
<script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app="app">
    <h1>Dangerous API DEMO</h1>
    <pre>{{data | json}}</pre>
  </body>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...