Błąd CORS: "żądania są obsługiwane tylko dla schematów protokołu: http ..." itd

Próbuję uruchomić prostą aplikację. Mam backend Express, który zwraca ciąg JSON, gdy odwiedzono go w localhost:4201/ticker. Po uruchomieniu serwera i złożeniu prośby o ten link z mojego serwisu Angular przez http, pojawia się następujący błąd:

XMLHttpRequest nie może załadować localhost:4201/ticker. Pochodzenie krzyżowe żądania są obsługiwane tylko dla schematów protokołów: http, data, chrome, chrome-rozszerzenie, https.

Przeczytałem następujący artykuł: zrozumienie i korzystanie z CORS i jak stwierdzono, wykorzystano moduł cors z moim serwerem express. Jednak nadal otrzymuję błąd, jak podano powyżej. Część kodu podana jest poniżej:

Kod serwera:

private constructor(baseUrl: string, port: number) {
    this._baseUrl = baseUrl;
    this._port = port;
    this._express = Express();
    this._express.use(Cors());
    this._handlers = {};
    this._hInstance = new Handlers();
    this.initHandlers();
    this.initExpress();
}
private initHandlers(): void {
    // define all the routes here and map to handlers
    this._handlers['ticker'] = this._hInstance.ticker;
}
private initExpress(): void {
    Object.keys(this._handlers)
        .forEach((key) => {
            this._express.route(this._url(key))
                .get(this._handlers[key]);
        });
}
private _url(k: string): string {
    return '/' + k;
}

Oto funkcja obsługi:

ticker(req: Request, res: Response): void {
    Handlers._poloniex
        .getTicker()
        .then((d) => {
            return Filters.tickerFilter(d, Handlers._poloniex.getBases());
        })
        .then((fdata) => {

            //res.header('Access-Control-Allow-Origin', "*");
            //res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
            res.header('Content-Type', 'application/json');
            res.send(JSON.stringify(fdata));
        })
        .catch((err) => {
           this._logger.log([
                'Error: ' + err.toString(),
                'File: ' + 'handlers.class.ts',
                'Method: ' + 'ticker'
            ], true);
        });   
}

Oto moja usługa kątowa:

export class LiveTickerService {

  private _baseUrl: string;
  private _endpoints: {[key:string]: string};

  constructor(
    private _http: Http
  ) {
    this._baseUrl = 'localhost:4201/';
     this._endpoints = {
       'ticker': 'ticker'
     };
   }

  getTickerData(): Observable<Response> {
    return this._http.get(this._baseUrl + this._endpoints['ticker'])
      .map(resp => resp.json())
  }

}

Oto jak korzystam z mojej Usługi:

getTicker() {
  let a = new Array<{[key: string]: any}>();
  this._tickerService.getTickerData()
     .subscribe(
        data => {
          let parsed = JSON.parse(JSON.stringify(data));
          Object.keys(parsed)
            .forEach((k) => {
              a.push({k: parsed[k]});
            });
         this.data = a;
        },
        error => console.log(error.toString()),
        () => console.log('Finished fetching ticker data')
      );
  return this.data;
}
Author: Viktor Borítás, 2017-09-16

1 answers

XMLHttpRequest nie może załadować localhost:4201/ticker. Pochodzenie krzyżowe żądania są obsługiwane tylko dla schematów protokołów: http, data, chrome, chrome-rozszerzenie, https.

Za każdym razem, gdy widzisz wiadomość "only supported for protocol schemes" , prawie na pewno oznacza to, że zapomniałeś umieścić https lub http na adresie URL żądania w swoim kodzie.

Więc w tym przypadku poprawką jest użycie adresu URL http://localhost:4201/ticker w kodzie tutaj:

this._baseUrl = 'http://localhost:4201/';

...bo bez http:// tam, localhost:4201/ticker nie jest tak naprawdę adres URL, który zamierzasz.

 143
Author: sideshowbarker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-16 21:38:13