当前位置: 首页 > 知识库问答 >
问题:

Http拦截器没有正确接收Http标头[重复]

左丘嘉木
2023-03-14

在谷歌搜索了5个小时后,我找不到任何问题的答案。我有一个用于auth服务的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(

        );
      }



}

角拦截器和CORS也是这样吗

共有1个答案

蓬弘
2023-03-14

您需要将拦截器注册到app.module.ts中,如下所示。首先inport it从'@angull/common/http'导入{HTTP_INTERCEPTORS};并将以下行

 providers: [
   {
      provide: HTTP_INTERCEPTORS,
      useClass: JwtInterceptor,
      multi: true
    }
}
 类似资料:
  • 问题内容: 这个想法是在某些情况下从另一个来源获取数据,所以我有这个存根: 失败了 [$ injector:cdep]找到循环依赖项:拦截器<-$ http 还尝试注入$ injector并使用它获取$ http,结果相同。有任何想法吗? .config就是声明: 问题答案: 注入到: 用它来获取回调函数中返回的对象。 这是一个例子

  • 我正在使用servlet 3.0和Jetty编写HTTPS代理服务器。 如何在码头处理HTTPS Connect? 目前我正在使用jetty maven插件,我的插件配置如下- 是-我想在同一端口上处理HTTP和HTTPS。当我启动Jetty时,一切都很好- 我对doGet和doPost进行了@覆盖,当我发送HTTP请求时,这两种方法都很好。但是当客户端发送HTTPS Connect时,它们都不会

  • 配置拦截器 declarations: [ AppComponent ], HttpClientModule ], providers: [ [ { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true } ] bootstrap:

  • 问题内容: 我似乎无法让$ httpProvider.interceptors实际进行拦截。我在JSFiddle上创建了一个示例,该示例记录了拦截器运行的时间以及$ http响应成功的时间。在成功返回响应之后,将运行请求拦截器。这似乎有些倒退。 我不能使用transformRequest,因为我需要更改配置中的参数。该部分未显示在示例中。 我正在使用AngularJS 1.1.5 http://j

  • 我无法在控制台记录时在拦截器中获取自定义响应头。控制台记录了拦截器httpResponse "控制台日志响应" HTTP响应{标头: HttpHeaders,状态: 200, statusText:"OK", ok: true,...} HttpHeaders lazyInit:ƒ()lazyUpdate:null normalizedNames:Map(0){}proto:Object ok:t

  • 问题内容: 我正在尝试使用s拦截器为我的网站编写一个通用错误处理程序,但它们似乎无法执行我想做的事情。 我放置了拦截器,但是当服务器处于脱机状态/未响应时,它们从未被调用(net :: ERR_CONNECTION_REFUSED)。我了解为什么会发生这种情况,因此没有响应可拦截。 我想知道是否有捕获这些错误的一个通用的方法,比听其他的回调为每个请求。 问题答案: 您可能可以检查ResponseE