Web-application(Angular, deployed to IIS) needs to interact with some IoT via API. IoT based on ESP8266 and API run under ESP8266WebServer library. For each request at the backend level, I send back the CORS header
server.on(F("/settings"), HTTP_GET, getSettings);
server.on(F("/settings"), HTTP_POST, updateSettings);
server.on(F("/settings"), HTTP_OPTIONS, sendCORS);
....
void getSettings()
{
server.sendHeader("Access-Control-Allow-Origin", "*", true);
.....
}
void sendCORS()
{
server.sendHeader("Access-Control-Allow-Origin", "*", true);
server.send(200);
}
So, my issue is next: pre-flight request(OPTIONS) complete success, return status 200 and necessary header, but in same next GET request failed with reason:
Access to XMLHttpRequest at 'http://192.168.1.100/settings' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field cors is not allowed by Access-Control-Allow-Headers in preflight response.
Frontend service:
getSettings(): Observable<any> {
return this.requestBuilder.setApiUrl(environment.kitchenLedApi +'/settings')
.get();
}
//builder
@Injectable()
export class RequestBuilderService {
private url = '';
private defaultHeaders = new HttpHeaders({
'Accept': 'application/json',
'Content-Type': 'application/json',
'Cors': 'Access-Control-Allow-Origin'
});
constructor(private readonly httpClient: HttpClient) { }
public setApiUrl(url: string) {
this.url = url;
return this;
}
public get<T>(params?: { [param: string]: string | string[] }): Observable<T> {
return this.httpClient
.get<T>(this.url, {
headers: this.defaultHeaders,
params: params
});
}
}
Could you please assist with this issue?
Reading from the error given to you by the browser, the request that you've made after the preflight request contains a header (named Cors
) that was not defined in the Access-Control-Allow-Headers
header value in the server's response to the preflight request.
If there's some specific reason for you to send custom headers to the server, then these should be announced with the Access-Control-Request-Headers
header. The server should then check this list of values and send back the ones that are allowed with the Access-Control-Allow-Headers
header. If there is a mismatch, the browser will not make the subsequent request. That said, I don't see the need to send any CORS related headers manually by the client to the server. This should be handled by the browser and server exclusively. So perhaps simply remove the Cors
header from the default headers that you append in the service.