I am attempting to use HttpClient to get a json return from a file that I have locked using htaccess and htpasswd on my web server. I can run the get/post request on postman with the Authorization header and it returns fine. When I run it in angular, I get the error in the title along with a 401 error.
Here is the function that triggers the HttpRequest
getConfig(): Observable<any> {
return this.http.get('myurlhere/myfile.json', { responseType: 'json' })
}
Here is my interceptor – and yes, the console.log fires and logging the result shows the the request with the headers appended.
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor() { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
req = req.clone({
setHeaders: {
'Authorization': 'Basic XXXXXXXXXXXXXXXXXXXXXXX'
}
})
console.log('INTERCEPTED')
return next.handle(req);
}
}
There are a lot of similar issues here, but nothing seems to be working. The 401 return is labeled OPTIONS and I’ve pieced together what that means, just can’t find a way around it.
2
Answers
FIX It ended up being an issue server-side with htaccess and CORS setup.
I needed to add the
LimitExcept
block, then it started working!It seems there is an issue with the
request
, therequest
object (req
) is immutable, so you have to define a new property and clone the request to it, then update itcheck the docs for more info
hope it helps