【发布时间】:2020-03-20 04:06:34
【问题描述】:
在谷歌搜索 5 小时后,我找不到任何问题的答案。 我有一个用于身份验证服务的 Http 拦截器,它阻止了对外部 API 的请求(没有拦截器它工作得很好)
代码...
拦截器
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AuthenticationService } from '../services/auth.service';
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(private authenticationService: AuthenticationService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// add authorization header with jwt token if available
const currentUser = this.authenticationService.currentUser();
if (currentUser && currentUser.token) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${currentUser.token}`,
Accept: 'text/plain; charset=utf-8',
}
});
}
return next.handle(request);
}
}
组件
import { Component, OnInit, ViewChildren, QueryList, ViewEncapsulation } from
'@angular/core';
import { FormBuilder, Validators, FormGroup } from '@angular/forms';
// import { Router, ActivatedRoute } from '@angular/router';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
// import { of, Observable } from 'rxjs';
import { CursI } from './curs.model';
import { CursService } from './../curs.service';
@Component({
selector: 'curs-valutar',
templateUrl: './curs.component.html',
styleUrls: ['./curs.component.scss'],
providers: [CursService]
})
/**
* InventoryList component - handling the inventorylist with sidebar and content
*/
export class CursComponent implements OnInit {
curs: object;
curslist: Array<CursI>;
currency: string = '';
date: string = '';
entity: string = '';
cursLaData: Array<string> = [];
C: string = '';
Currency: Array<string> = ['USD', 'EURO', 'Coroane suedeze'];
validationform: FormGroup;
constructor(private modalService: NgbModal, public formBuilder: FormBuilder, private service: CursService) {
this.validationform = this.formBuilder.group({
date: [''],
currency: ['']
});
}
ngOnInit() {
// this._fetchData();
}
saveData() {
const date = this.validationform.get('date').value;
let currency = this.validationform.get('currency').value;
this.curs = {
date,
currency,
};
if(this.validationform && currency === 'USD')
{this.currency = 'usd'} else if (this.validationform && currency === 'EURO')
{this.currency = 'eur'}
else {this.currency = 'sek'}
this.modalService.dismissAll();
this.date = date.replace(/-/g, '/');
this.entity = this.date + '/' + this.currency + '.bnr';
this.service.findCurs(this.entity).subscribe((data: any) => {
(data => this.cursLaData = data);
console.log(data);
});
console.log(this.cursLaData);
console.log(this.curs);
console.log(this.date);
console.log(this.currency);
console.log(this.entity);
}
/**
* Modal Open
* @param content modal content
*/
openModal(content: string) {
this.modalService.open(content, { centered: true, size: 'sm' });
}
onSubmit(values: object, form, modal) {
if (values) {
//post
this.saveData();
this.closeModal(form, modal);
}
}
closeModal(form, modal) {
form.reset();
modal('close');
}
}
服务
import { Injectable, PipeTransform } from '@angular/core';
import { CursModule } from './curs.module';
import { HttpClient, HttpHeaders, HttpParams, HttpResponse } from '@angular/common/http';
@Injectable({
providedIn: 'root',
})
export class CursService {
private apiurl = 'http://www.infovalutar.ro/';
public entity: string;
data: string;
headers = new HttpHeaders().set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS').set('Content-Type', 'text/plain').set('Accept', 'text/plain').set('Access-Control-Allow-Headers', '*');
httpOptions = {
headers: this.headers,
};
constructor(private httpClient: HttpClient) {
}
public findCurs(entity: string) {
return this.httpClient.get(`${this.apiurl}${entity}`, this.httpOptions).pipe(
);
}
}
错误 curs:1 从源 'http://localhost:4200' 访问 XMLHttpRequest 在 'http://localhost:4200' 已被 CORS 策略阻止:在预检响应中 Access-Control-Allow-Headers 不允许请求标头字段 access-control-allow-headers . core.js:7187 ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://www.infovalutar.ro/2019/11/19/usd.bnr", ok: false, ...}
【问题讨论】:
-
如果您尝试使用来自另一个站点的 ajax 访问资源,浏览器中会出现 CORS 错误。远程服务器 CORS 策略中不允许将
Authorization或Accept作为标头。您必须检查/修改远程服务器的配置以允许 CORS 请求中的这些标头。 -
删除前端 JavaScript 代码中添加“access-control-allow-headers”请求标头的任何部分。 Access-Control-Allow-Headers 是响应标头,而不是请求标头。尝试将其设置为请求标头将导致问题中引用的错误。
标签: angular http cors http-headers interceptor