【问题标题】:Angular2 error in getting JSON from external URL using JSONP使用 JSONP 从外部 URL 获取 JSON 时出现 Angular2 错误
【发布时间】:2017-04-18 06:29:39
【问题描述】:

Angular2 中,我正在向 Indeed 求职API 发出获取请求以获取工作列表,但我收到以下错误:

拒绝执行脚本 'http://api.indeed.com/ads/apisearch?publisher=&q=java&l=austin&v=2&format=json' 因为它的 MIME 类型('application/json')是不可执行的,并且 已启用严格的 MIME 类型检查。

我的组件中的代码是:

import { Component } from '@angular/core';
import { Headers, Jsonp, URLSearchParams } from '@angular/http';

@Component({
    templateUrl: 'jobs.html'
})
export class JobsPage {

    constructor(
        private jsonp: Jsonp
    ) { }

    private headers = new Headers({ 'Content-Type': 'application/json' });

    ngOnInit() {

        this.jsonp.get('http://api.indeed.com/ads/apisearch?publisher=<my_publisher_id>&q=java&l=austin&v=2&format=json', { headers: this.headers })
            .map(res => res.json())
            .subscribe((data) => {
                console.log(data);
            },
            (e) => { console.log(e); }
            );
    }
}

【问题讨论】:

  • 好吧,你期待的 json 但你想把它变成 jsonp ,那是行不通的。
  • 你试过了吗? 2&format=jsonp ????
  • 我认为您还需要将内容类型更改为此“:application/javascript
  • 格式只有两个值,即jsonxml
  • 不适用于内容类型应用程序/javascript

标签: angular jsonp


【解决方案1】:

JSONP 通常带一个callback 参数来指向一个全局方法来执行结果,它应该是一个JavaScript 脚本返回Content-Type: application/javascript

这没有记录,但从源代码中我们推断您需要添加另一个带有文字值的参数:

&callback=JSONP_CALLBACK

没有这个参数,Indeed API 返回application/json。附加它,你会得到application/javascript

另外,删除您添加到请求中的标头 Content-Type,因为不发送任何内容就不需要它。这不会影响响应,只会影响请求的解释方式。 (及时,无论实现如何,JSONP 都不接受任何标头。)

来源:jsonp_backend.ts

更新:

因为 Angular Jsonp 会为回调生成一个复合名称 (object.method),而我们想要完成任务,所以解决方案是使用 3rd-party 库来处理 jsonp。

这是一个简单的:https://github.com/camsong/fetch-jsonp

fetchJsonp('http://api.indeed.com/ads/apisearch?publisher=<my_publisher_id>&q=java&l=austin&v=2&format=json')
  .then(function(response) {
    return response.json()
  }).then(function(json) {
    console.log('parsed json', json)
  }).catch(function(ex) {
    console.log('parsing failed', ex)
  })

请注意,您不能使用 JSONP 发送标头。 Angular 的 Jsonp 对此具有误导性。而且你有一个承诺,而不是一个可观察的。

【讨论】:

  • 我已经尝试过了,但得到了同样的错误。我已删除标头内容类型并将回调变量添加到 URL。拒绝执行来自 'api.indeed.com/ads/…' 的脚本,因为它的 MIME 类型('application/json')不可执行,并且启用了严格的 MIME 类型检查。
  • 此 URL 返回 application/javascript: api.indeed.com/ads/…。与您的网址有何不同?
  • 这可能是一个错误。 Angular 在回调名称上使用.,api 似乎不接受:api.indeed.com/ads/…
  • 我的网址是:http://api.indeed.com/ads/apisearch?publisher=&lt;id&gt;&amp;q=java&amp;l=austin&amp;v=2&amp;format=json&amp;callback=JSONP_CALLBACK
  • 有一个未解决的问题。不是您的 URL,而是 Angular 用来发出请求的修改后的 URL。问题:github.com/angular/angular/issues/13175
猜你喜欢
  • 2017-05-01
  • 2015-11-24
  • 1970-01-01
  • 2023-02-11
  • 2018-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多