我在量角器e2e中具有以下代码段。使用基本身份验证调用REST API端点会导致“ HTTP 401未经授权”。
import {HttpClient, HttpXhrBackend, XhrFactory, HttpErrorResponse, HttpHeaders} from '@angular/common/http';
import { XMLHttpRequest} from 'xmlhttprequest';
export class BrowserXhr implements XhrFactory {
constructor() {}
build(): any {
return <any > (new XMLHttpRequest());
}
}
describe('test: ', () => {
const http: HttpClient = new HttpClient(new HttpXhrBackend(new BrowserXhr()));
it('test', (done) => {
let headers_object = new HttpHeaders();
headers_object.append('Content-Type', 'application/json');
headers_object.append('Authorization', 'Basic my_auth_key');
const httpOptions = {
headers: headers_object
};
http.post('https://exp.com', {
name: 'aa',
i: 'aa'
}, httpOptions).subscribe((response: any) => {
expect(response.message).toEqual('success');
done();
}, (error: HttpErrorResponse) => {
done.fail(error.message);
});
});
});
答案 0 :(得分:0)
我如下更改了http标头,为我工作。
const headersObject = new HttpHeaders({'Content-Type': 'application/json', Authorization: 'Basic my_auth_key'});