I’ve been stuck for days without a solution. I tried to implement automatic token renewal for accessing the Insee API in my Angular project, but despite my configuration, I keep receiving the error:
“Access to XMLHttpRequest at ‘https://api.insee.fr/token’ from origin ‘http://localhost:XXXX’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.”
I even tried hardcoding the access token that I generated directly on the page, but nothing works. Could you please help me out?
Here is my code:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, switchMap } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class InseeService {
private apiUrlSiret = 'https://api.insee.fr/entreprises/sirene/V3.11/siret';
private apiUrlSiren = 'https://api.insee.fr/entreprises/sirene/V3.11/siren';
private tokenUrl = 'https://api.insee.fr/token';
private consumerKey = 'XXXX';
private consumerSecret = 'XXXX';
constructor(private http: HttpClient) {}
private getToken(): Observable<any> {
const headers = new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + btoa(`${this.consumerKey}:${this.consumerSecret}`)
});
const body = new URLSearchParams();
body.set('grant_type', 'client_credentials');
return this.http.post(this.tokenUrl, body.toString(), { headers });
}
getEnterpriseInfo(identifier: string): Observable<any> {
return this.getToken().pipe(
switchMap((tokenResponse: any) => {
const token = tokenResponse.access_token;
const headers = new HttpHeaders({
'Authorization': `Bearer ${token}`
});
const apiUrl = identifier.length === 14 ? this.apiUrlSiret : this.apiUrlSiren;
return this.http.get(`${apiUrl}/${identifier}`, { headers });
})
);
}
}