angular - Http 拦截器在 Angular 中未正确接收 http 标头
问题描述
谷歌搜索 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
'@角/核心';
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 ”访问“ http://www.infovalutar.ro/2019/11/19/usd.bnr ”的 XMLHttpRequest已被 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 , …}
Angular拦截器和CORS的情况相同
解决方案
您需要像这样将拦截器注册到 app.module.ts 中。首先导入它
import { HTTP_INTERCEPTORS } from '@angular/common/http';
并放置这些行
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: JwtInterceptor,
multi: true
}
}
推荐阅读
- css - flexbox调整子宽度应该只改变下一个兄弟宽度
- python - Github,为什么我的 python 代码有 ^M 而没有新行?
- .htaccess - 将 http,非 www 重定向到 https,将 www 用于子文件夹
- r - 如何使用 Power BI 在 R 中的 ggplot (geom_point) 上显示数据标签?
- sql - SQL Server SUM(添加)产品配件的价格
- python - xml.etree.Elementree:为什么标签下面的文本没有被识别
- ios - 隐藏stackView时打破约束
- shell - 用于在字符串值中插入双引号并作为值保存到数组的 shell 脚本模式
- java - 使用构造函数注入模拟弹簧类
- c++ - 组合 SUM Max 5 因子 C++