![](/img/trans.png)
[英]Angular 2 http request: how to set Authorization with username, password and domain
[英]how to set authorisation header with username & password in angular4
我正在遠程使用Java Rest API服務。 他們將發送用戶名和密碼以及授權服務。 在這里我正在使用angular6,而我傳遞的標頭存在問題。 下面是我的代碼
import { Injectable } from '@angular/core';
import { HttpClient,HttpHeaders} from '@angular/common/http';
import { Http, Response } from '@angular/http';
import { Observable, Subject } from 'rxjs';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { HttpModule } from '@angular/http';
`
@Injectable()
export class MasterService{
constructor(private http:HttpClient) { }
getApi(url): Observable<any> {
let headers = new HttpHeaders();
headers = headers.append('Content-Type', 'application/json');
headers = headers.append("Authorization", "Basic YWRtaW46YWRtaW4=");
headers = headers.append('Access-Control-Allow-Origin', '*');
headers = headers.append('UserName', 'admin');
headers = headers.append('password', 'admin');
return this.http.get(url,{ headers:headers })
.map((res) => {
console.log(res);
return res;
}).catch(this.handleErrorObservable);
}
}
`
我有這樣的錯誤
OPTIONS http://publicIp/coms/getEnterpriseCutomerDtls?custid=10 401
(Unauthorized)
Access to XMLHttpRequest at 'http://publicIp/coms/getEnterpriseCutomerDtls?
custid=10' from origin 'http://localhost:4200' has been blocked by
CORSpolicy: Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested
resource.
提前致謝
我前段時間也有相同的問題,請參見此處: angular-2-authentication-headers
在標頭授權中,您必須已經在其中加密了用戶名和密碼,如下所示:
headers = headers.append('Authorization', 'Basic ' + btoa(username + ':' + password));
並始終確保在后端正確配置了您的CORS策略,因此,我遇到了多個問題...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.