gpt4 book ai didi

angular - 使用 tomcat 的 Angular CORS

转载 作者:行者123 更新时间:2023-11-28 23:16:44 25 4
gpt4 key购买 nike

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

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

最佳答案

在您的 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>

关于angular - 使用 tomcat 的 Angular CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48478201/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com