Angular 2基本身份验证无效

Pet*_*ter 24 header basic-authentication typescript angular

我正在尝试使用Angular2连接/对API执行POST请求,这是一个带有基本身份验证密码的非常简单的API.在api上禁用密码时,一切都按预期工作.但是当我启用基本身份验证时,Angular无法再连接到API.在邮递员一切正常.我尝试了以下但没有成功.

我有两个标题"Content-Type"和"Authorization"

headers.append("Content-Type", "application/x-www-form-urlencoded");
Run Code Online (Sandbox Code Playgroud)

我试过这两个标题.

headers.append("Authorization", "Basic " + btoa(Username + ":" + Password)); 
headers.append("Authorization", "Basic VXNlcm5hbWU6UGFzc3dvcmQ=");
Run Code Online (Sandbox Code Playgroud)

我唯一能找到的是,在RAW请求标头中只有一行包含标题名称,但缺少值:

Access-Control-Request-Headers: authorization, content-type
Run Code Online (Sandbox Code Playgroud)

原始标题:

#Request Headers
OPTIONS /shipment HTTP/1.1
Host: api.example.com
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36
Access-Control-Request-Headers: authorization, content-type
Accept: */*
Referer: http://localhost:4200/address
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,nl;q=0.6
Run Code Online (Sandbox Code Playgroud)

希望有人能提供帮助

Pie*_*Duc 26

简化版本,可为您的请求添加自定义标头:

import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';

@Injectable()
export class ApiService {

   constructor(private _http: Http) {}

   call(url): Observable<any> {
      let username: string = 'username';
      let password: string = 'password';
      let headers: Headers = new Headers();
      headers.append("Authorization", "Basic " + btoa(username + ":" + password)); 
      headers.append("Content-Type", "application/x-www-form-urlencoded");
      return this._http.post(url, data, {headers: headers})
    }
}
Run Code Online (Sandbox Code Playgroud)

很难确定你出错的地方,因为缺少http你实际通话的代码.但是这个例子对你有用