【问题标题】:CORS in angular using tomcat使用tomcat的角度CORS
【发布时间】:2018-07-06 18:53:53
【问题描述】:

我有自己的 Angular 5 项目,我有一个 HTTP 拦截器组件,用于在所有请求的标头中添加身份验证,还有一个服务来调用自定义服务器 API。 当我使用 HTTP 时,我的休息服务工作正常(当然我在我的 tomcats 的 web.xml 中添加了 cors 过滤器)但是我的 HTTP 拦截器组件没有捕获它,但是当我使用 httpClient 它会抛出 HTTP 拦截器组件但服务器响应是“请求的资源上不存在‘Access-Control-Allow-Origin’标头”。 你能帮帮我吗?

    import { Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';

import { Http, Headers, Response, RequestOptions, RequestMethod } from 
'@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import { HttpClient, HttpHeaders } from '@angular/common/http';

const API_URL = environment.apiUrl;

@Injectable()
export class RestService {

constructor(private http: HttpClient) { }

private handleError (error: Response | any) {
console.error('ApiService::handleError', error);
return Observable.throw(error);
}


public getAll(input: any, url: string): Observable<any> {

return this.http
  //.get('http://httpbin.org/headers')
  .post(API_URL + url, input)
  .map(response => {
    const returnedData = response;
    return returnedData;
  })
  .catch(this.handleError);
}

}

import { Injectable, Injector } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpHeaders } 
from '@angular/common/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';


@Injectable()
export class HttpinterceptorComponent implements HttpInterceptor {
constructor() { }

intercept(req: HttpRequest<any>, next: HttpHandler): 
Observable<HttpEvent<any>> {

console.log('intercepted request ... ');

const headers = new HttpHeaders({
  'sessionId': 'token 123',
  'Content-Type': 'application/json'
});


// Clone the request to add the new header.
const authReq = req.clone({headers});

console.log('Sending request with new header now ...');

// send the newly created request
return next.handle(authReq)
.catch((error, caught) => {
  // intercept the respons error and displace it to the console
  console.log('Error Occurred');
  console.log(error);
  // return the error to the method that called it
  return Observable.throw(error);
}) as any;
}
}

【问题讨论】:

  • 您遇到了服务器问题。它没有按照应有的方式在响应中设置 Access-Control-Allow-Origin 标头。

标签: angular tomcat cors angular5


【解决方案1】:

在您的 tomcat 过滤器中,您需要添加以下内容并传播配置更改。

<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

【讨论】:

  • 感谢您的回复,正如我所说,我在我的 tomcat 的 web.xml 中添加了这个,当我使用 HTTP 发送请求时,我的服务器接受我的请求,但是当我使用 httpClient 我的服务器的响应是没有“Access-Control-Allow-Origin”标头
  • 启用了吗?您的 servlet 无法使用它
  • 抱歉,我无法理解您的问题“是否已启用?”的含义,但我将该过滤器放在 web.xml 文件中,服务器接受我的本地主机请求,但是当我更改 HTTP 模块时从“@angular/common/http”到 httpClient 模块,我得到了 CORS 错误
【解决方案2】:

几周后终于找到了解决方案,如果您在后端使用 Spring MVC,您可以通过扩展 WebMvcConfigurerAdapter 来启用 CORS 过滤器,而无需任何服务器配置

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

   @Override
   public void addCorsMappings(CorsRegistry registry) {
       registry.addMapping("/**");
   }
}

并将 CorsOrigin 放在您的控制器或您的特定方法上

@CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)

CORS support in Spring Framework

Enabling Cross Origin Requests for a RESTful Web Service

【讨论】:

    猜你喜欢
    • 2017-11-10
    • 2020-02-29
    • 2014-01-02
    • 2015-10-27
    • 2018-02-08
    • 2021-04-27
    • 1970-01-01
    • 1970-01-01
    • 2016-09-17
    相关资源
    最近更新 更多