Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"JSONP injected script did not invoke callback." #8153

Closed
mbakker96 opened this issue Apr 20, 2016 · 27 comments
Closed

"JSONP injected script did not invoke callback." #8153

mbakker96 opened this issue Apr 20, 2016 · 27 comments

Comments

@mbakker96
Copy link

I created a JSONP request in angular 2 / ionic 2 to get a json object but when I run it I get a error in my console.

This is the code where I make the reqeust

this._jsonp.get('http://jsfiddle.net/echo/jsonp/')
   .map(res => res.json())
   .subscribe(data => console.log(data), error => console.log(error));

Current behavior
Gives an error:

{
     "_body":"JSONP injected script did not invoke callback.",
     "headers":  "Headers",
     "status": 200,
     "statusText": "Ok",
    " type": 3,
     "url": "http://jsfiddle.net/echo/jsonp/"
}

Expected/desired behavior
Return an empty JSON object: { }

Other information
I run angular 2 beta 14 with ionic 2.

@templth
Copy link

templth commented Apr 20, 2016

You didn't provide the callback in your request. In the following sample, the query parameter to provide the callback is c (it actually depends on the service). You always need to provide the JSONP_CALLBACK value for such parameter.

var url = 'https://accounts.google.com/logout?c=JSONP_CALLBACK';
jsonp.request(url, { method: 'Get' })
 .subscribe((res) => {
   (...)
 });

@mbakker96
Copy link
Author

@templth nope still an error

this._jsonp.request('http://localhost:3000/calendar/2016/4', { method: 'Get' })
            .subscribe(
                (data) => {
                    console.log(data);
                },
                (error) => {
                    console.log(error);
                });

and this is in my app.js for nodejs server

app.get('/calendar/:year/:month', function (request, response) {

    response.jsonp(createYear(2016)); // returns  an object

)};

@MurhafSousli
Copy link

Did you get a solution, I have the same problem

@wesleycho
Copy link
Contributor

I was able to recreate this problem in a Plunker here.

What looks like is happening is that this._finished is never toggled as true, and so this block of code always runs:

if (!this._finished) {
let responseOptions =
new ResponseOptions({body: JSONP_ERR_NO_CALLBACK, type: ResponseType.Error, url});
if (isPresent(baseResponseOptions)) {
responseOptions = baseResponseOptions.merge(responseOptions);
}
responseObserver.error(new Response(responseOptions));
return;
}
. @robwormald @jeffbcross this looks like an outright bug in JsonpConnection_ - I think some logic needs to be added where upon completion of the request (whether aborted, completed, or cancelled), it has to call this.finished.

This also seems to indicate that the error message is busted even in the event the request is aborted or cancelled.

@galziv
Copy link

galziv commented Jun 6, 2016

in http.umd.js on line 1425 you have the following code:

               if (url.indexOf('=JSONP_CALLBACK&') > -1) {
                    url = StringWrapper.replace(url, '=JSONP_CALLBACK&', "=" + callback + "&");
                }

This means you must have the string '=JSONP_CALLBACK&' in your url for angular to replace the JSONP_CALLBACK string with its generate function which eventually will call your success function upon success.

@templth
Copy link

templth commented Jun 6, 2016

mbakker96: Since you use the jsonp method of Express on the server side, the default name of the callback is callback:

this._jsonp.request('http://localhost:3000/calendar/2016/4?callback=JSONP_CALLBACK', { method: 'Get' })
            .subscribe(
                (data) => {
                    console.log(data);
                },
                (error) => {
                    console.log(error);
                });

@templth
Copy link

templth commented Jun 6, 2016

@wesleycho In fact I don't think that there is a problem here. The callback is internally managed by Angular2 but you need to specify the JSONP_CALLBACK value for it.

Under the hood Angular2 will update the URL like this:

http://jsfiddle.net/echo/jsonp/?callback=__ng_jsonp__.__req0.finished

This way the finished method within the JSONPConnection_ class will be called and the _finished property set to true.

See this plunkr: http://plnkr.co/edit/Sn7ml5Omzoz3DrnumCnt?p=preview.

@sambanthar
Copy link

sambanthar commented Sep 27, 2016

for angular 2 stable latest release jsonp crud sample please

@sambanthar
Copy link

which you told is right. i need to fix backend api

@vicb vicb closed this as completed Sep 27, 2016
@kvieira90
Copy link

Still think this issue should be in the Angular 2 documentation for others trying to use jsonp to sidestep cors issues or leverage jsonp

@PrabhakaranD
Copy link

I am a newbie to Angular 2. I am really confused. I am using .NET Web Api as my server code and it returns Json data. On the client end, i am fetching the data using Jsonp. I am able to see the data coming (Status : 200) using Inspect element Network tab in Chrome. But my returned Observables from service flowing to the error section in my subscribe method. Below is the error message. Please help me out.

Note: I do have a function mycallback in my service.

errorMessage:
Object
_body:
JSONP injected script did not invoke callback.
status:
200
ok:
true
statusText:
Ok
type:
3
url:
http://diffDomain.com/api/test?mycallback=__ng_jsonp__.__req6.finished

@Nicholas-Westley
Copy link

It sounds like what is confusing you is what confused me. Your function does not need to be called "mycallback". It needs to pass back the json data in a function whose name angular passes in mycallback. In this case "_ng_jsonp.__req6.finished". After unpacking the json angular receives back _ng_jsonp.__req6.finished({mystuff:'yeah'}). It is possible I am doing it wrong but after a day banging my head against the wall it works

@sambanthar
Copy link

in the backend you return data must be present this following form
ex: [in php]
echo $_GET['callback'] . '('.json_encode($result).')';

@PrabhakaranD
Copy link

Thanks guys. @sambanthar @Nicholas-Westley

Earlier my api gives me Json data instead of Jsonp.
I reconfigured it so that it returns Jsonp and It WORKS.

@zxc19890923
Copy link

url: "http://localhost:8000/?callback=__ng_jsonp__.__req0.finished"
_body: "JSONP injected script did not invoke callback."

@MurhafSousli
Copy link

@templth I specified the callback, and I still have the problem

_body:"JSONP injected script did not invoke callback."
headers:Headers
ok:true
status:200
statusText:"Ok"
type:3
url: "http://ng2.disqus.com/count-data.js?2=https://murhafsousli.github.io/ng2-disqus/&callback=__ng_jsonp____req0_finished"

@woaisancai
Copy link

i solved the problem:use __ng_jsonp__.__req${this.times}.finished instead of 'JSONP_CALLBACK'
export class WikipediaService {
constructor(private jsonp: Jsonp) {
this.times=0;}
search (term: string) {
let wikiUrl = 'http://en.wikipedia.org/w/api.php';
let params = new URLSearchParams();
params.set('search', term); // the user's search value
params.set('action', 'opensearch');
params.set('format', 'json');
params.set('callback', __ng_jsonp__.__req${this.times}.finished);
this.times=this.times+1;
// TODO: Add error handling
return this.jsonp
.get(wikiUrl, { search: params })
.map(response => <string[]> response.json()[1]);
}
}

@HauntedSmores
Copy link

Anything on this? Same issue.

let params = new URLSearchParams;
params.set('callback', 'JSONP_CALLBACK');
request = this.instaBase + "?access_token=" + this.instaToken;
this.jsonp.get(request, {search: params }).map(response => response.json());

JSONP injected script did not invoke callback

@zxc19890923
Copy link

@templth
right:
params.set("callback", "ng_jsonp.__req0.finished");
params.set("callback", "ng_jsonp.__req1.finished");
error:
params.set("callback", "JSONP_CALLBACK");

Why can not call Angular2's JSONP_CALLBACK handler?

@zxc19890923
Copy link

@woaisancai

If a page contains multiple components, jump to another route, and then return to the original page, $ {this.times} can not be calculated, there will be an error, why JSONP_CALLBACK can not call the angular2 inside the processing function?

@danmcclure
Copy link

danmcclure commented Feb 18, 2017

Angular is replacing JSONP_CALLBACK with
__ng_jsonp____req0_finished
but it should be
__ng_jsonp__.__req0.finished

Inspect your Network response. If you see __ng_jsonp____req0_finished({...json object...}) this is the problem.

Also, some services have different requirements for the callback query string parameter, which proves to be nasty because the error is exactly the same. I was using &callback=__ng_jsonp__.__req0.finished with MailChimp which produced the same error but the response had only a json object and no callback function. This is because MailChimp's spec is to use &c= instead of &callback=

@danmcclure
Copy link

When hardcoding the Jsonp callback (re: JSONP_CALLBACK issue) you need to account for the number of calls made, as Angular persists the state of each call. An example of what I'm doing for Mailchimp:

addEmailToList(email: string, listId: string, jsonpCalls: number, callback: any) {   

const cbJsonp = '__ng_jsonp__.__req' + jsonpCalls + '.finished';

let url = [
      'http://',
      host,
      '/subscribe',
      '/post-json',
    ].join('');

let queryParams: URLSearchParams = new URLSearchParams();
queryParams.set('u', Config.MAILCHIMP_API_KEY);
queryParams.set('id', listId);
queryParams.set('EMAIL', email);
queryParams.set('c', cbJsonp);  // non-standard; varies by service; usually 'callback'
...
}

@vipulupadhyay
Copy link

vipulupadhyay commented Mar 24, 2017

This solution i have used on instagram rest api call
this._InstUrl = "your url";

let params1 = new URLSearchParams();
//params.set('search', term); // the user's search value
//params.set('action', 'opensearch');
params1.set('format', 'json');
//params1.set('callback', "ng_jsonp.__req0.finished");
params1.set('callback', "JSONP_CALLBACK");

    return this._jsonp
        .get(this._InstUrl, { search: params1 })
        .map(response => { debugger; this.Result = response.json().data })
        .subscribe(
        (data) => {
            debugger
            console.log(this.Result);
        },
        (error) => {
            debugger
            console.log(error);
        });

This one working plz check

@DenSchiep
Copy link

Is there any update on this issue? The issue I am having is simular to the issue @danmcclure already mentioned. Except when using the _'ng_jsonp._req' + jsonpCalls + '.finished'-trick I still get the same error.

So, the call is succesfull but again JSONP injected script did not invoke callback. is the error which is returned when trying to subscribe...

@Devmikola
Copy link

No found solution for this.
In library everethyng seems normaly. But this:
JSONPConnection_.prototype.finished = function (data) { // Don't leak connections this._finished = true;
Will not execute, and finished with value false raise an error "JSONP_ERR_NO_CALLBACK = 'JSONP injected script did not invoke callback.';".
The result in the Network Response contains needed data "JSONP_CALLBACK?(["Amsden, OH, United States","Amstelveen, NH, Netherlands","Amsterdam, MO, United States","Amsterdam, NH, Netherlands","Amsterdam, NY, United States","Amsterdam, OH, United States","Amston, CT, United States"]);".
Actualy i must to use another api without jsonp.
Waiting for solution.

@arunkumarsp
Copy link

Is there any solutions for this ?? i am trying in ng-4. Whichever way we try we are getting the same old error
Response {_body: "JSONP injected script did not invoke callback.", status: 200, ok: true, statusText: "Ok", headers: Headers, …}

@angular-automatic-lock-bot
Copy link

This issue has been automatically locked due to inactivity.
Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

This action has been performed automatically by a bot.

@angular-automatic-lock-bot angular-automatic-lock-bot bot locked and limited conversation to collaborators Sep 12, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests