【发布时间】: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