Reputation: 1097
I have this small app asking a service to an API. I have set the credentials like this:
this.http.get<Response>(url, {
headers: new HttpHeaders().set('Authorization', 'Basic '
+ btoa('C7YHKF91RAABYXNK :JMGYBMAT1X18KA2W '))
})
.subscribe(data => {
Response = data['results'];
There's a 401 and then a 200 and the API is not returning what was suposed to return (a png image). On Edge, when I hit submit, the browser asks for the token. I input the credentials and then the service works (chrome is similar)...Yesterday everything was working fine, but now I have this problem. Is it the API? Are the headers wrongly set up? I have a live demo for testing here. Thanks for the help!
EDIT as suggested by @Mudassar
onSubmit({ valid }: { valid: boolean }, f: any) {
if {//
}
else {
let color = encodeURIComponent(this.params.handwriting_color);
const url =
`https://api.handwriting.io/render/png?handwriting_id=${this.params.handwriting_id}&text=${this.params.text}&handwriting_size=${this.params.handwriting_size}&handwriting_color=${color}`;
//SET HEADERS
let headers= new HttpHeaders();
headers.append('Authorization', 'Basic ' + btoa('C7YHKF91RAABYXNK :JMGYBMAT1X18KA2W '))
headers.append("Access-Control-Allow-Origin", "new[] { (string)context.Request.Headers['Origin'] }");
headers.append("Access-Control-Allow-Headers", "new[] { 'Origin, X-Requested-With, Content-Type, Accept, Authorization' }");
headers.append("Access-Control-Allow-Methods", "new[] { 'GET, POST, PUT, DELETE, OPTIONS' }");
headers.append("Access-Control-Allow-Credentials", "new[] { 'true' }");
//REQUEST
this.http.get<Response>(url, {
headers: headers
})
.subscribe(data => {
Response = data['results'];
}, (err: HttpErrorResponse) => {
if (err.error instanceof Error) {
console.log('An error occurred:', err.error.message);
} else {
console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
console.log(Response);
}
});
}
But I still get the 401...
Upvotes: 0
Views: 82
Reputation: 3225
This might be due to not setting the CORS
Access-Control-Allow-Headers: Authorization
further setting this should ensure proper working
headers.append("Access-Control-Allow-Origin", new[] { (string)context.Request.Headers["Origin"] });
headers.append("Access-Control-Allow-Headers", new[] { "Origin, X-Requested-With, Content-Type, Accept, Authorization" });
headers.append("Access-Control-Allow-Methods", new[] { "GET, POST, PUT, DELETE, OPTIONS" });
headers.append("Access-Control-Allow-Credentials", new[] { "true" });
EDIT: Starting to feel the problem might be to do with the server side hence suggesting to add on the server side to expose the Authorization header.
"Access-Control-Expose-Headers" : "Authorization"
Upvotes: 1