1

I am trying to make a jsonp request in Angular 1.6 to get json data from a webservice. (URL censored here)

var url = ...;
var trustedUrl = $sce.trustAsResourceUrl(url);


$http.jsonp(trustedUrl, { jsonpCallbackParam: 'angularcallbacks_0' })
.then(function (data) {
    console.log(data);
});

If I execute this, I get the following error: Uncaught SyntaxError: Unexpected token :.

But in the "Sources"-Tab of the Chrome-Dev-Tool I can see the following response in valid json. enter image description here

In addition, I see following error in the console:

Possibly unhandled rejection: {"data":false,"status":404,"config":{"method":"JSONP","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"angularcallbacks_0","url":{},"headers":{"Accept":"application/json, text/plain, */*"}},"statusText":"error"}

What's the problem with my code? Thank you!

Daniel
  • 3,541
  • 3
  • 33
  • 46
J. Doe
  • 11
  • 2
  • "the following response in valid json" — Well, that's the problem then. You're using `jsonp()` so the response has to be valid JSONP and not JSON. – Quentin Mar 02 '18 at 08:13
  • 1
    JSONP is a rather nasty hack to work around the Same Origin Policy, we've had CORS for years now so you really should use that instead. It is much safer, easier to debug, and more powerful. – Quentin Mar 02 '18 at 08:15
  • I have no access to the server, so how should I use CORS? – J. Doe Mar 02 '18 at 08:33
  • The same way that you would use JSONP: Persuade whomever controls the server to support it. – Quentin Mar 02 '18 at 08:34
  • The owner told me to use JSONP. I think there is no way I can persuade him to use CORS, as he probably won't care. – J. Doe Mar 02 '18 at 08:38
  • If you're stuck using JSONP, then you're stuck using it. The URL you are using is not JSONP though. – Quentin Mar 02 '18 at 08:41
  • I'm very grateful you still answer my questions! Thank you very much, I'm new to this subject and you really help me. – J. Doe Mar 02 '18 at 08:47
  • I now changed my code to the following and now I'm getting jsonp as result. `$http.jsonp($sce.trustAsResourceUrl("...?callback=angularcallback"), { jsonpCallbackParam: 'angularcallback' }) .then(function (data) { console.log(data); });` – J. Doe Mar 02 '18 at 08:51
  • This is the error I get now `Uncaught ReferenceError: angularcallback is not defined at ...?callback=angularcallback&angularcallback=angular.callbacks._0:1` – J. Doe Mar 02 '18 at 08:51

0 Answers0