Angular 6 - httpClient 在 httpOptions 中传递基本身份验证

Angular 6 - httpClient passing basic auth in httpOptions

我在 Angular 6 有一项服务,我正在尝试更改记录,但它说我没有被授权。

现在我有这个:

const httpOptions = {
  headers: new HttpHeaders({'Content-Type': 'application/json'})
};

  update(id, title, content) {
    const updateData = { id: id, title: title, content: content };
      return this.http.put(`http://myurl/${id}`, updateData, httpOptions);
  }

我的问题是:

如何将基本授权添加到我的 httpOptions 或直接将其添加到更新方法?

只需像这样在 headers 中添加您的 token/authorization -

let httpHeaders = new HttpHeaders()
              .set('authorization', this.authorizationHeaderValue)
              .set('Content-Type', application/json); 

Both have methods such as set and append. set constructs a new body with a new value and append constructs a new body with an appended value

PS:这里我假设变量 (this.authorizationHeaderValue) 值包含 BearerBasic 或任何需要的值,相应地更改它。

更多信息请阅读此处

您可以在headers中添加基本授权,如下所示:

var headers_object = new HttpHeaders();
headers_object.append('Content-Type', 'application/json');
headers_object.append("Authorization", "Basic " + btoa("username:password"));

const httpOptions = {
  headers: headers_object
};

查看 angular.io 文档,非常简单。

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': 'Basic my-auth-token'
  })
};

您可以像以前一样使用 httpOptions 常量。

更多信息:https://angular.io/guide/http#adding-headers

PS:这是一种适用于小型或快速应用的方法,如果您想构建更强大的应用,请考虑使用自动添加授权 header 的 HTTP 拦截器苍蝇.

在 httpOptions 中传递基本身份验证的 httpClient 在 Angular 6

中有所不同
let httpHeaders= new HttpHeaders();
httpHeaders.append('Content-Type', 'application/json');
httpHeaders.append("Authorization", "Basic " + btoa("username:password"));

const httpOptions = {
  headers: httpHeaders
};

update(id, title, content) {
    const updateData = { id: id, title: title, content: content };
      return this.http.put(`http://myurl/${id}`, updateData, httpOptions);
  }
import { HttpClient, HttpHeaders } from '@angular/common/http';

var headers = new HttpHeaders();

var token = localStorage.getItem('token');

headers.append('Content-Type', 'application/json');

headers.append("Authorization", "Basic " + token));

const httpOptions = {
  headers: headers
};
const httpOptions = {
  headers: new HttpHeaders(
    {
      'Content-Type': 'application/json',
      'Authorization': `Basic ` + btoa('user:password'),
    }
  )
};


return this.http.post<any>(
      `apilink`,{},
      httpOptions
    ).pipe(map(res => {
      return res;
}));

许多服务器需要额外的 headers 来进行保存操作。例如,服务器可能需要授权令牌或“Content-Type”header 来显式声明请求的 MIME 类型 body。在您的情况下,您可以通过以下代码进行基本授权。

import { HttpHeaders } from '@angular/common/http'; 
const httpOptions = {headers: new HttpHeaders({
'Content-Type':  'application/json',
Authorization: 'my-auth-token' })};

您可以在发出下一个请求之前更新授权header

httpOptions.headers =  httpOptions.headers.set('Authorization', 'my-new-auth-token');