I have a service in Angular 6 and I'm trying to change a record but it's saying I'm not authorized.
Right now I have this:
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);
}
My question is:
How to I add basic authorization to my httpOptions or do I add it direct to the update method?
You can add basic authorization by appending it in headers, as below:
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
};
Looking at the angular.io documentation, it's pretty straightforward.
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Basic my-auth-token'
})
};
And you can use the httpOptions
constant as you did.
For more information: https://angular.io/guide/http#adding-headers
Just add your token/authorization in the headers like this -
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: Here I am assuming the variable (this.authorizationHeaderValue) value is included value like Bearer
or Basic
or whatever needed, Change it accordingly.
For more read here
来源:https://stackoverflow.com/questions/50694913/angular-6-httpclient-passing-basic-auth-in-httpoptions