I have a problem with angular HTTP module, I have a backend API developed with Lumen (URL: http://localhost/api/public/), protected with a bearer token, but when I try to load JSON response in my angular app (URL: http://localhost:4200/), I have this message in my console :
Failed to load http://localhost/api/public/links: Response to the preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 401.
I have param my API to say 401 it's Authorization header not found, 402 Bearer token not found and, 403 for the invalid token. (I will change all with a 401 error when my problem will be solved)
I found that it's CORS problem, so I add these lines in my .htaccess :
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
But I still have a 401 error in my console despite the fact that I have an HTTP interceptor which adds authorization header in all my HTTP request :
Failed to load http://localhost/api/public/links: Response for preflight has invalid HTTP status code 401.
I had not the problem when I test my API with Postman, this is my code:
HTTP interceptor
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor() {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const req = request.clone({ setHeaders: { Authorization: 'Bearer test' } });
return next.handle(req);
}
}
Service
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
import { Link } from '../class/link';
@Injectable({
providedIn: 'root'
})
export class LinkService {
constructor(private http: HttpClient) {}
private resourceUrl = 'http://localhost/api/public/links';
getAll (): Observable<Link[]> {
return this.http.get<Link[]>(this.resourceUrl).pipe(
retry(3),
catchError(this.handleError('getAll', []))
);
}
private handleError<T> (operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
console.error(error);
return of(result as T);
};
}
}
Thanks in advance!
Access-Control-Allow-headers in the response from your server? And have you configured the server to deal with the OPTIONS preflight? - user184994Authorizationinto your list of allowed headers - user184994Lumenand server config correctly to allow preflight to go through, you may change your question tag. - Chybie