【问题标题】:Angular 6 error: JSONP injected script did not invoke callbackAngular 6 错误:JSONP 注入脚本未调用回调
【发布时间】:2019-05-26 22:08:57
【问题描述】:

从事 Angular 6 项目并尝试访问公共 API,因此我需要使用 JSONP 来绕过 CORS。我的代码出现以下错误: “错误:JSONP 注入脚本未调用回调”。 我认为是回调参数的名称有问题。

我在这里和 Github 上花了很多时间研究类似的问题,最值得注意的是:https://github.com/angular/angular/issues/8153 并尝试将 JSONP_CALLBACK 替换为:

ng_jsonp.__req${this.times}.finished

__ng_jsonp____req6_finished

完全省略回调参数

但我还没有找到成功。

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from "rxjs/operators";

export class CoursesAPIService {

    constructor(private http: HttpClient) {}

    getData() {
        var url = 'http://web-app.usc.edu/web/soc/api/classes/?callback=JSONP_CALLBACK'
        console.log("calling: " + url)

        return this.http.jsonp(url, "callback")
           .pipe(map(data => {
               console.log("Inside map")

               console.log(data)
           })
        ).subscribe()
    }
}    

【问题讨论】:

    标签: angular angular6 jsonp angular-httpclient


    【解决方案1】:

    我遇到了类似的问题,结果证明我在使用 HttpClient.jsonp() 时不应该传递 callback=JSONP_CALLBACK 参数和值。

    // try this instead
    var url = 'http://web-app.usc.edu/web/soc/api/classes/?'
    

    如果你查看 angular github https://github.com/angular/angular/blob/master/packages/common/http/src/client.ts中的源代码

    1121 1461 行(由于本节正在编写中,仍然只需搜索 jsonp() 函数)您会注意到他们会发送该参数再次。你当前的 url 变量将变成:

    // this is what's probably giving you issues after the jsonp function's internal functions are processed 
    'http://web-app.usc.edu/web/soc/api/classes/?callback=JSONP_CALLBACK&callback=JSONP_CALLBACK'
    

    【讨论】:

      猜你喜欢
      • 2017-10-20
      • 2016-11-11
      • 2019-04-01
      • 2016-12-16
      • 2017-06-16
      • 2020-02-22
      • 2014-02-05
      • 2012-02-16
      • 2014-12-31
      相关资源
      最近更新 更多