Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
866 views
in Technique[技术] by (71.8m points)

typescript - Angular 2 Basic Authentication not working

I'm trying to connect/ do a POST request to an API with Angular2, It's a very simple API with a Basic Authentication password. When disabling the password on the api everything works like expected. But when I enable the Basic Authentication Angular can no longer connect to the API. In Postman everything works. I tried the following without success.

I've got two headers "Content-Type" and "Authorization"

headers.append("Content-Type", "application/x-www-form-urlencoded");

I've tried these two headers.

headers.append("Authorization", "Basic " + btoa(Username + ":" + Password)); 
headers.append("Authorization", "Basic VXNlcm5hbWU6UGFzc3dvcmQ=");

The only thing I can find is that in the RAW request headers there's only a line with the header names but the values are missing:

Access-Control-Request-Headers: authorization, content-type

Raw headers:

#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

Hope someone can help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Simplified version to add custom headers to your request:

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})
    }
}

It's hard to determine where you went wrong, because the lack of code of the actual http call you do. But this example should work for you


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...