Angular 4 http CORS 没有带有 Java servlet 的“Access-Control-Allow-Origin”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44925449/
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-12 01:48:20  来源:igfitidea点击:

Angular 4 http CORS No 'Access-Control-Allow-Origin' with a java servlet

javaangularservlets

提问by Nau Parejaa Escamilla

I'm trying to do a http.post but chrome is showing the following error:

我正在尝试执行 http.post,但 chrome 显示以下错误:

No Access-Control-Allow-Origin.

没有访问控制允许来源。

My Angular function is:

我的角函数是:

onSubmit(event: Event) {
  event.preventDefault();
    this.leerDatos()
    .subscribe(res => {
      //datos = res.json();
      console.log("Data send");
    }, error => {
          console.log(error.json());
      });



  }

  leerDatos(): Observable<any> {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    return this.http.post(`http://localhost:8080/LegoRepositoryVincle/CoreServlet`, { name: "bob" }, options)
                    //.map(this.extractData)
                    //.catch(this.handleError);
  }

And my servlet doPost method includes:

我的 servlet doPost 方法包括:

response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.addHeader("Access-Control-Allow-Origin","http://localhost:4200");
response.addHeader("Access-Control-Allow-Credentials", "true");
response.addHeader("Access-Control-Allow-Methods","GET,POST");
response.addHeader("Access-Control-Allow-Headers","X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept, Cache-Control, Pragma");

回答by AndreaM16

If you still want to use CORS while developing you can solve this kind of issue using angular/cli --proxy-config.

如果您在开发时仍想使用 CORS,您可以使用angular/cli --proxy-config解决此类问题。

Essentially, if you want to make requests to a remote machine having, for example, nginxweb server running, you perform all your calls to your very same application, e.g. localhost:4200(default in angular/cli). Then you redirect those responses to your server using --proxy-config.

本质上,如果您想向远程机器发出请求,例如,运行nginxweb 服务器,您可以对相同的应用程序执行所有调用,例如localhost:4200(angular/cli 中的默认值)。然后,您使用 将这些响应重定向到您的服务器--proxy-config

Let's suppose your server's api have all the /apiprefix entrypoint. You need to create a file called proxy.config.jsonin the root of your project and configure it like:

假设您的服务器的 api 具有所有/api前缀入口点。您需要在项目的根目录中创建一个名为proxy.config.json的文件并将其配置为:

{
    "/api" : {
        "target" : "http://xx.xxx.xxx.xx", // Your remote address
        "secure" : false,
        "logLevel" : "debug", // Making Debug Logs in console
        "changeOrigin": true
    }
}

And then, all your http requests will point to localhost:4200/api/.

然后,您所有的 http 请求都将指向localhost:4200/api/.

Finally, you should be done by running ng server --proxy-config proxy.config.json.

最后,您应该通过运行来完成ng server --proxy-config proxy.config.json

If you notice that some headers are missing in the request, add them from your web server or edit your http.service.tsto append those like in this example:

如果您注意到请求中缺少某些标头,请从您的 Web 服务器添加它们或编辑您的http.service.ts以追加如下示例中的标头:

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { isNull } from 'lodash';

@Injectable()
export class HttpClientService {

  private _host: string;
  private _authToken: string;
  private _options: RequestOptions = null;

  constructor(private _http: Http, private _config: AppConfig, private _localStorageService: LocalStorageService) {
      this._host = ''; // Your Host here, get it from a configuration file
      this._authToken = ''; // Your token here, get it from API
  }

  /**
   * @returns {RequestOptions}
   */
   createAuthorizationHeader(): RequestOptions {
      // Just checking is this._options is null using lodash
      if (isNull(this._options)) {
        const headers = new Headers();
        headers.append('Content-Type', 'application/json; charset=utf-8');
        headers.append('Authorization', this._authToken);
        this._options = new RequestOptions({headers: headers});
      }
      return this._options;
   }

   /**
    * @param url {string}
    * @param data {Object}
    * @return {Observable<any>}
    */
    get(url?: string, data?: Object): Observable<any> {
      const options = this.createAuthorizationHeader();
      return this._http.get(this._host + url, options);
    }

   /**
    * @param url {string}
    * @param data {Object}
    * @return {Observable<any>}
    */
    post(url?: string, data?: Object): Observable<any> {
      const body = JSON.stringify(data);
      const options = this.createAuthorizationHeader();
      return this._http.post(this._host + url, body, options);
    }

}

So, you would perform all of your api calls through this service like

因此,您将通过此服务执行所有 api 调用,例如

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpClientService } from './http.service.ts';

export class TestComponent implements OnInit {

  _observable: Observable<any> = null;

  constructor(private _http: HttpClientService) { }

  ngOnInit() {
      this._observable = this _http.get('test/')
                .map((response: Response) => console.log(response.json()));
  }

}

Angular 5 Update:

角 5 更新

In app.module.tsnow you need to replace import { HttpModule } from '@angular/http';with import { HttpClientModule } from '@angular/common/http';.

app.module.ts现在,你需要更换import { HttpModule } from '@angular/http';import { HttpClientModule } from '@angular/common/http';

The service changes a bit to:

服务稍有变化:

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

@Injectable()
export class HttpClientService {

  private _host: string;
  private _authToken: string;
  private __headers: HttpHeaders;

  constructor(private _http: HttpClient, private _config: AppConfig, private _localStorageService: LocalStorageService) {
      this._host = ''; // Your Host here, get it from a configuration file
      this._authToken = ''; // Your token here, get it from API
  }

  /**
   * @returns {HttpHeaders}
   */
   createAuthorizationHeader(): HttpHeaders {
      // Just checking is this._options is null using lodash
      if (isNull(this.__headers)) {
        const headers = new HttpHeaders()
           .set('Content-Type', 'application/json; charset=utf-8')
           .set('Authorization', this. _authToken || '');
        this.__headers= new RequestOptions({headers: headers});
      }

      return this.__headers;
   }

   /**
    * @param url {string}
    * @param data {Object}
    * @return {Observable<any>}
    */
    get(url?: string, data?: Object): Observable<any> {
      const options = this.createAuthorizationHeader();
      return this._http.get(this._host + url, {
          headers : this.createAuthorizationHeader()
      });
    }

   /**
    * @param url {string}
    * @param data {Object}
    * @return {Observable<any>}
    */
    post(url?: string, data?: Object): Observable<any> {
      const body = JSON.stringify(data);
      const options = this.createAuthorizationHeader();
      return this._http.post(this._host + url, body, {
          headers : this.createAuthorizationHeader()
      });
    }
}

回答by Kodjo Tchioffo

You may use Angular CLI proxy tooling for this purpose.

为此,您可以使用 Angular CLI 代理工具。

  • 1. you create a file proxy.config.json at the root of your project
  • 2. you map your API URLs to target URLs using this syntax
  • 1.你在你的项目根目录创建一个文件proxy.config.json
  • 2. 使用此语法将 API URL 映射到目标 URL
 "/api/xxxxxxx" : {
        "target" : "http://www.api.com/xxxxxxx", 
        "secure" : false,
        "logLevel" : "debug",
        "changeOrigin": true
    }
  • 3. Serve your application using
  • 3. 使用
ng serve --proxy-config proxy.config.json