javascript - Angular 在 HttpClient.get header 中设置授权

标签 javascript angular httpclient

import {Component, OnInit} from '@angular/core';
import {HttpClient, HttpErrorResponse, HttpResponse} from '@angular/common/http';

@Component({
  selector: 'git',
  templateUrl: './git.component.html'
})

export class GitComponent implements OnInit {
  constructor(private http: HttpClient) {
  }
  ngOnInit(): void {
    const headers = {authorization: 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJzYXNobyIsImF1dGgiOiJST0xFX1VTRVIiLCJleHAiOjE1MjQwODcyMzJ9.MUv5RgI9LxQyrrCfjfX8HR2-XiQmz4vjLqH7V_0Du7VFLC0WrK_y3FfeNoT2Nj_uguIK2ss7jv-LNiHuCGtz4A'};
    this.http.get('http://localhost:8080/links/all', headers)
      .subscribe((e) => {
        console.log(e);
      }, (err: HttpErrorResponse) => {
        console.log(err);
      });
  }
}

http.get中如何设置授权?我想使用保存在 const headers 中的不记名 token 。就这样。谢谢

编辑:我忘了提及,我想知道如何在这里手动设置它而不是使用拦截器,所有教程都带有拦截器,所以我无法弄清楚

最佳答案

试试这个:

import {Component, OnInit} from '@angular/core';
import {HttpClient, HttpErrorResponse, HttpResponse} from '@angular/common/http';

@Component({
  selector: 'git',
  templateUrl: './git.component.html'
})

export class GitComponent implements OnInit {
  constructor(private http: HttpClient) {
  }
  ngOnInit(): void {
    const headers =  'Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJzYXNobyIsImF1dGgiOiJST0xFX1VTRVIiLCJleHAiOjE1MjQwODcyMzJ9.MUv5RgI9LxQyrrCfjfX8HR2-XiQmz4vjLqH7V_0Du7VFLC0WrK_y3FfeNoT2Nj_uguIK2ss7jv-LNiHuCGtz4A';
    this.http.get('http://localhost:8080/links/all', {
      headers: new HttpHeaders().set('Authorization', headers )
    })
      .subscribe((e) => {
        console.log(e);
      }, (err: HttpErrorResponse) => {
        console.log(err);
      });
  }
}

关于javascript - Angular 在 HttpClient.get header 中设置授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49894036/

相关文章:

javascript - JS给对象添加属性

angular - 如何将 trix-editor 集成到 Angular 2 应用程序中?

java - 针对网站的 http client head 方法返回 503 但该网站运行正常

javascript - Angular2 - 有条件创建的输入字段的表单验证

带有其他参数的 C# HttpClient Post 字符串数组

Android 向服务器发送 HTTP POST 请求

javascript - 为什么将 React 组件存储为变量或状态是不好的设计实践

javascript - 如何查询外部域,将其存储在chrome扩展中,并调用它以在popup.html中显示?

javascript - 如何在静态站点上动态呈现社交分享按钮的元标记?

Angular 2 : Can focusin and focusout be in one event?