【问题标题】:I'm getting an http header (access denied) error even though I have set up my httpheaders即使我已经设置了我的 httpheaders,我仍然收到一个 http 标头(访问被拒绝)错误
【发布时间】:2019-10-12 14:13:45
【问题描述】:

我有一个使用 Spring Boot API 从数据库调用的用户列表。

这些用户中的每一个都有各种属性,如用户名、id、名字、姓氏、注册日期和个人资料照片,其中上传文件的 id(上传后托管在 spring 项目主文件夹中的子文件夹中)在另一个名为 files 的数据库表中。

要获取图像,您必须使用正确的 JWT 令牌(您在登录后获得)并使用路径:'http://localhost:8082/downloadFile/' + imageid

在上面提到的用户列表下,我创建了一个 div,单击具有所选用户属性的用户之一后将填充该 div,并显示实际的用户个人资料图片。

我发现了一篇关于如何将图像链接转换为实际照片的 stackoverflow 帖子,因此我关注了the instructions

问题是在执行了答案中所写的操作后,我不断收到此错误:

ERROR Error: 
"Uncaught (in promise): HttpErrorResponse: { 
    "headers": { 
        "normalizedNames:{},
        "lazyUpdate":null 
     },
     "status":403,
     "statusText":"OK",
     "url":"http://localhost:8082/downloadFile/e508e9c1-75e4-4cf4-86a8-fc617e4cc292",
     "ok":false,
     "name":"HttpErrorResponse",
     "message":"Http failure response for http://localhost:8082/downloadFile/e508e9c1-75e4-4cf4-86a8-fc617e4cc292: 403 OK", 
    "error":{}
}"

这是我的 .ts 组件:

import { Component, OnInit } from '@angular/core';
import { ViewEncapsulation } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { UserService } from '../user.service';
import { MatDialog, MatDialogConfig, MatTableDataSource } from '@angular/material';
import { NewDialogComponent } from '../new-dialog/new-dialog.component';
import { DomSanitizer } from '@angular/platform-browser';
import { map } from 'rxjs-compat/operator/map';
import { Observable, Observer } from 'rxjs';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['../app.component.scss', './dashboard.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class DashboardComponent implements OnInit {
  loginuser: any = {};
  imgSrc: any = {};
  users: any[] = [];
  public dataSource = new MatTableDataSource<User>();
  displayedColumns = ['id', 'username', 'email', 'firstname', 'lastname', 'registeredDate', 'enabled'];
  constructor(private service: UserService, private http: HttpClient, private sanitizer: DomSanitizer) {
  this.loginuser = JSON.parse(localStorage.getItem('currentUser'));
  this.service.getAllUsers(this.loginuser.token).subscribe(u => {
  this.dataSource.data = u as User[];
  console.log('datasource: ', this.dataSource.filteredData);
  this.users = u;
  console.log('user: ', this.users);
  });
 }

ngOnInit() {
}

onRowClicked(selectedItem) {
  console.log('selected item: ', selectedItem);
  document.getElementById('msg').style.display = 'none';
  document.getElementById('info').style.display = 'block';
  if (selectedItem.photoProfile === 'http://localhost:8082/static.images/user/default.jpg') {
  this.imgSrc = 'C:/Users/Adam/Documents/CODE/Ang/StarAdmin-Free-Angular-Admin-Template/src/assets/default.jpg';
} else if (selectedItem.photoProfile === 'null') {
  console.log('null');
} else {
  const currentUser = JSON.parse(localStorage.getItem('currentUser'));
  console.log(currentUser.token);
  this.getFile('http://localhost:8082/downloadFile/' + selectedItem.photoProfile, currentUser.token);
}
}

getFile(url: string, token): any {
const headers = new HttpHeaders({'Authorization': 'Bearer ' + token});
this.http.get(url, {
  responseType: 'blob',
})
  .toPromise()
  .then((res: any) => {
    let blob = new Blob([res._body], {
      type: res.headers.get('Content-Type', headers)
    });

    let urlCreator = window.URL;
    this.imgSrc = this.sanitizer.bypassSecurityTrustUrl(
        urlCreator.createObjectURL(blob));
  });
}
}

export interface User {
id: number;
username: string;
firstName: string;
lastName: string;
email: string;
enabled: string;
registeredDate: Date;
}

【问题讨论】:

  • 对于和我有同样问题的人,你可能想检查this link

标签: html angular spring


【解决方案1】:

看起来你从来没有传入你在 GET 请求调用上方创建的 headers 对象。将您的请求更改为:

const headers = new HttpHeaders({'Authorization': 'Bearer' + token});

this.http.get(url, headers=headers, { 响应类型:'blob', })

【讨论】:

  • 当我这样做时,我得到“预期的 1-2 个参数,但得到了 3 个”
  • 您可能必须将您的 {responseType: 'blob'} 处理滚动到选项对象中。 get 方法需要两个位置参数:一个 url 和一个 Options 对象。 Options 对象接受多个属性,包括标题。有关使用更广泛的 Options 对象的示例,请参阅 this 帖子。
猜你喜欢
  • 2020-07-24
  • 2021-07-18
  • 1970-01-01
  • 1970-01-01
  • 2011-10-04
  • 1970-01-01
  • 2020-03-16
  • 1970-01-01
  • 2016-10-20
相关资源
最近更新 更多