【问题标题】:Not able to get data from `cross domain` because of `CORB` issue由于“CORB”问题,无法从“跨域”获取数据
【发布时间】:2018-12-17 06:18:09
【问题描述】:

我正在尝试从我的本地主机获取数据,如下所示:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable({
    providedIn: 'root'
})
export class SearchServiceService {

    apiRoot:string = 'https://itunes.apple.com/search';
    results:Object[];
    loading:boolean;

    constructor(private http:HttpClient) {
        this.results = [];
        this.loading = false;
    }

    search(term:string){
        let promise = new Promise((resolve, reject) => {
            let apiURL = `${this.apiRoot}?term=${term}&media=music&limit=20`;
            this.http.get(apiURL).toPromise().then(res => {
                // console.log( res.json() );
                resolve();
            }, function(error){
                console.log('error is', error);
            })
        });
        return promise;
    }
}

我正在使用Chrome 浏览器。为了防止CORS 问题,我使用了这个扩展:

https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi/related?hl=en-US

但仍然收到错误:

Failed to load https://itunes.apple.com/search?term=Moo&media=music&limit=20: The 'Access-Control-Allow-Origin' header contains multiple values 'http://evil.com/, *', but only one is allowed. Origin 'http://localhost:4200' is therefore not allowed access.

zone.js:2969 Cross-Origin Read Blocking (CORB) blocked cross-origin response https://itunes.apple.com/search?term=Moo&media=music&limit=20 with MIME type text/javascript. See https://www.chromestatus.com/feature/5629709824032768 for more details.

没有得到数据。我需要在这里做哪些更改?有人帮我吗?

【问题讨论】:

  • @anyone - 而不是只是把down vote 寻找一些帮助
  • CORS 阻止您获取数据。如果服务器不让您进入,那么您是否通过 chrome 启用也没关系,那么您就不会获得任何数据
  • 如果我只是通过浏览器窗口中的 url,我正在获取数据..
  • 我在这里概述了一个适合我的解决方案。 stackoverflow.com/questions/47345282/…
  • 有没有人找到解决办法

标签: angular angular6


【解决方案1】:

我认为目前最好的选择是在 http 选项中指明以文本数据形式获取响应。浏览器 corb 算法将忽略文本数据。

const httpOptions = {
  headers: new HttpHeaders({
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  }),
  responseType: 'text' as 'json'
}

...

search(term:string){
    let promise = new Promise((resolve, reject) => {
        let apiURL = `${this.apiRoot}?term=${term}&media=music&limit=20`;
        this.http.get(apiURL, httpOptions).toPromise().then(res => {
            // console.log( res.json() );
            resolve();
        }, function(error){
            console.log('error is', error);
        })
    });
    return promise;
}

然后由您将响应数据解析回 json。在修改订阅者调用中的数据时,浏览器 corb 算法似乎仍然处于活动状态。

如果您想进一步使用它,您可能必须将其保存到类变量并从那里解析它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-21
    • 2016-06-21
    • 2019-08-05
    • 2021-02-27
    • 1970-01-01
    • 2019-01-31
    • 2018-11-25
    • 2019-02-07
    相关资源
    最近更新 更多