J'essaye de faire une application simple. J'ai un backend Express qui, renvoie une chaîne JSON lors de la visite à localhost:4201/ticker
. Quand je lance le serveur et, faire une demande à ce lien de mon service angulaire sur http
, je reçois l'erreur suivante:Angular 4 CORS Erreur: "les requêtes ne sont supportées que pour les protocoles de protocole: http ..." etc
XMLHttpRequest cannot load localhost:4201/ticker. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
Je lis l'article suivant: Understanding and Using CORS et, comme indiqué, utilisé le module cors
avec mon serveur express. Cependant, je reçois toujours l'erreur comme indiqué ci-dessus. Une partie du code est donnée ci-dessous:
Code Serveur:
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;
}
est ici la fonction de gestionnaire:
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);
});
}
Voici mon service angulaire:
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())
}
}
Voici comment J'utilise mon service:
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;
}