Javascript CORS 错误:“请求仅支持协议方案:http...”等

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46258449/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:23:26  来源:igfitidea点击:

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

javascriptangularexpresscors

提问by Abrar Hossain

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:

我正在尝试运行一个简单的应用程序。我有一个 Express 后端,它在访问时返回一个 JSON 字符串localhost:4201/ticker。当我运行服务器并从我的 Angular 服务向此链接发出请求时http,我收到以下错误:

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

XMLHttpRequest 无法加载 localhost:4201/ticker。跨源请求仅支持以下协议方案:http、data、chrome、chrome-extension、https。

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

我阅读了以下文章:了解和使用 CORS并且如上所述,将该cors模块与我的快速服务器一起使用。但是,我仍然收到上面给出的错误。部分代码如下:

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:

这是我的 Angular 服务:

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

回答by sideshowbarker

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

XMLHttpRequest 无法加载 localhost:4201/ticker。跨源请求仅支持以下协议方案: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 httpsor httpon the request URL in your code.

每当您看到“仅支持协议方案”消息时,几乎肯定意味着您刚刚忘记将httpshttp放在代码中的请求 URL 上。

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

因此,在这种情况下,修复方法是http://localhost:4201/ticker在此处使用代码中的 URL :

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

…because without the http://there, localhost:4201/tickerisn't really the URL you intend.

…因为没有http://那里,localhost:4201/ticker就不是您想要的 URL。