Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

javascript - CORS Error: “requests are only supported for protocol schemes: http…” etc

I am trying to run a simple application. I have an Express backend which returns a JSON string when visited at localhost:4201/ticker. When I run the server and make a request to this link from my Angular Service over http, I get the following error:

XMLHttpRequest cannot load localhost:4201/ticker. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

I read the following article: Understanding and Using CORS and as stated, used the cors module with my express server. However, I am still getting the error as given above. Part of code is given below:

Server code:

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;
}

Here is the handler function:

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);
        });   
}

Here is my Angular Service:

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())
  }

}

Here is how I am using my 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;
}
question from:https://stackoverflow.com/questions/46258449/cors-error-requests-are-only-supported-for-protocol-schemes-http-etc

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

XMLHttpRequest cannot load localhost:4201/ticker. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

Any time you see that “only supported for protocol schemes” message, it almost certainly means you’ve just forgotten to put the https or http on the request URL in your code.

So in this case, the fix is to use the URL http://localhost:4201/ticker in your code here:

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

…because without the http:// there, localhost:4201/ticker isn’t really the URL you intend.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...