CORS:No' Access-Control-Allow-Origin'标题是Angular 2

时间:2016-08-18 09:32:38

标签: http angular cors

我试图实现一个进行PATCH Http调用的服务,它是我得到这个错误的唯一方法" No' Access-Control-Allow-Origin'标题存在"当我在chrome上检查开发工具时,我看到一个OPTION而不是PATCH,这是我的方法:

pauseTasksJobs(id, task){

//this.headers.append('Access-Control-Allow-Origin', 'application/json');
//this.headers.append('Accept', 'application/json');

  var url = this.home+ "tasks/" +task+ "/jobs/" + id ;
  var body = "{  \" status \"  : \"Pause\" }";
  //var body = "{ status : Pause }";
   console.log("this is my body: "+body) 

   var result;

    this._http.patch(url,body,this.requestOption).
    map(res => res.json())
    .subscribe(res => {
               result = res;
              console.log("this is my result: "+result);
    },  error=> console.error('Error: ' + error),()=>console.log("tasks mis en pause"));
}

在我的构造函数中,我设置标题内容如下:

headers = new Headers();
 requestOption = new RequestOptions({ headers: this.headers });

  private actionV: string;

  constructor(private _http: Http) {
    this.headers.append('Content-Type', 'application/json');
    this.headers.append('Accept', 'application/json');
    this.headers.append('Authorization', 'Basic ' + cookieValue);
  }

1 个答案:

答案 0 :(得分:0)

首先,以角度为补丁请求添加标题。

像这样:

headers.append('Content-Type', 'application/json');
headers.append('Content-Type', 'Access-Control-Allow-Headers');

并且不要忘记在http请求中添加标题,如下所示:

this.http
    .patch(url, JSON.stringify(payload), { headers: headers })
    ...

其次在你的tomcat配置中,你需要配置:

 <param-name>cors.allowOrigin</param-name>
    <param-value>*</param-value>
</init-param>
<init-param>
 <param-name>cors.supportedMethods</param-name>
    <param-value>GET, POST, OPTIONS, PATCH</param-value>
</init-param>
<init-param>
    <param-name>cors.supportedHeaders</param-name>
    <param-value>Accept, Origin, X-Requested-With, Content-Type, Last-Modified</param-value>
</init-param>
<init-param>
    <param-name>cors.supportsCredentials</param-name>
    <param-value>true</param-value>
</init-param>

PATCH上的Angular首先发送OPTIONS,然后我们需要在CORS中允许OPTIONS。

希望有帮助吗?