From react i call an actix api
async function richiesteFn() {
try {
const response = await fetch('https://exampleip/richieste', {
method: 'GET',
headers: {
Authorization: sessionStorage.getItem('auth0_token'),
},
});
const data = await response.json();
// console.log(data);
return data;
} catch (error) {
return error;
}
}
here is the actix api
#[get("/richieste")]
async fn richieste_srvc(req: HttpRequest) -> HttpResponse {
let authorization_present = req.headers().contains_key("Authorization");
if authorization_present {
let authorization = req.headers().get("Authorization").unwrap();
let auth_str = authorization.to_str().unwrap();
let validate_token_fn = validate_auth0_token(&auth_str);
if validate_token_fn.is_err(){
let error = validate_token_fn.unwrap_err();
let err_str = format!("{{ \"Error\": \"{}\" }}", error);
HttpResponse::Ok().body(err_str)
} else {
let str = mostra_richieste();
if str.is_err() {
let error = str.unwrap_err();
let err_str = format!("{{ \"Error\": \"Errore nella lista richieste: {}\" }}", error);
HttpResponse::Ok().content_type(ContentType::json()).body(err_str)
} else {
HttpResponse::Ok().content_type(ContentType::json()).body(str.unwrap())
}
}
} else {
let err_str = format!("{{ \"Error\": \"Authorization header not present\" }}");
HttpResponse::Ok().content_type(ContentType::json()).body(err_str)
}
}
here is actix start function
HttpServer::new(move || {
let logger = Logger::default();
let cors_allowed_origin = env::var("CORS_ALLOWED_ORIGIN").unwrap();
let cors = Cors::default()
.allowed_origin(&cors_allowed_origin);
App::new()
.wrap(logger)
.wrap(cors)
.service(login)
.service(validate_token)
.service(richieste_srvc)
})
if i remove the code down here from the react js request the api works
, {
method: 'GET',
headers: {
Authorization: sessionStorage.getItem('auth0_token'),
},
and i tried adding the Access-Control-Allow-Origin in the actix respone but still same error.
here is the complete error:
Access to fetch at 'https://exampleip/richieste' from origin 'https://exampleip' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.