如何在angular的api请求中使用授权头令牌进行认证?

问题描述 投票:0回答:1

我即将请求一个get调用来从我的服务器上检索数据。我已经启用了授权,在大多数请求中使用Bearer令牌。当我从服务器上请求某些东西时,我怎样才能包含这个?(我在这里做错了什么?请帮助我。)

举个例子,我有一个名为Categories.service.ts的文件,它将从服务器上获取分类。

@Injectable({
  providedIn: 'root'
})
export class CategoriesService {

  private _url: string = "http://ifsstudents.educationhost.cloud/v2/categories/list";

  constructor(private http:HttpClient) { }

  private token: string="Bearer eyJ0eXA....";

  getCategories():Observable<ICategory[]>{
    let header = new HttpHeaders().set(
      "Authorization",this.token
    );

    return this.http.get<ICategory[]>(this._url,{headers:header});
  }
}

我已经用Postman和Bearer token进行了测试,没有任何问题。enter image description here

以下是错误日志enter image description here

javascript angular bearer-token get-request
1个回答
1
投票

更改 CategoriesService 如下

@Injectable({
providedIn: 'root'
})
export class CategoriesService {

private _url: string = "/api/categories/list";

constructor(private http:HttpClient) { }

private token: string="Bearer eyJ0eXA....";

getCategories():Observable<ICategory[]>{
    let header = new HttpHeaders().set(
    "Authorization",this.token
    );

    return this.http.get<ICategory[]>(this._url,{headers:header});
}
}

在您的根目录下(与 src 文件夹)创建一个名为 proxy.conf.json 内容如下

{
  "/api/*": {
    "target": "http://ifsstudents.educationhost.cloud/v2",
    "secure": true,
    "logLevel": "debug",
    "changeOrigin": true,
    "pathRewrite": {
      "^/api": ""
    }
  }
}

启动应用程序时,要注意

ng serve --proxy-config proxy.conf.json -o

密切关注控制台,查看路径转换是否正确。你应该看到如下内容

[HPM] Rewriting path from "/api/categories/list" to "/categories/list" [HPM] GET /api/categories/list ~> http://ifsstudents.educationhost.cloud/v2

如果您打算将其生产化,您需要在 ifsstudents.educationhost.cloud

© www.soinside.com 2019 - 2024. All rights reserved.