0

I'm trying to make a GET method to my PHP API. In order to do that, I have this code:

export class PerfilComponent {
  perfil: any;
  constructor(private http: HttpClient) { }
  ngOnInit() {
    const token:string | null = localStorage.getItem('token')
    console.log(token)
    const headers = new HttpHeaders({'api_key': token!})

    this.http.get("http://localhost:8000/api/usuario/mi-usuario", {headers})
      .subscribe(
        resultado => {
          this.perfil = resultado;
        }
      );
    console.log(this.perfil)
  }

The API needs the token to be send through header. This is the error I get everytime I try to send the GET request:

Access to XMLHttpRequest at 'http://localhost:8000/api/usuario/mi-usuario' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

I'll put the PHP code, maybe the error is in there, but I don't think so since while trying on Postman it did work well:

#[Route('/api/usuario/mi-usuario', name: 'app_mi_usuario', methods: ['GET'])]
    #[OA\Tag(name: 'Usuario')]
    #[Security(name: "apikey")]
    #[OA\Response(response:200,description:"successful operation" ,content: new OA\JsonContent(type: "array", items: new OA\Items(ref:new Model(type: UsuarioDTO::class))))]
    public function miUsuario(UsuarioRepository $usuarioRepository,
                                  Request $request,Utilidades $utils): JsonResponse
    {

        if ($utils->comprobarPermisos($request,1)) {
            $apikey = $request->headers->get("apikey");
            $id_usuario = Token::getPayload($apikey)["user_id"];
            $usuario = $usuarioRepository->findOneBy(array("id"=>$id_usuario));

            return $this->json($usuario, 200, [], [
                AbstractNormalizer::IGNORED_ATTRIBUTES => ['__initializer__', '__cloner__', '__isInitialized__'],
                ObjectNormalizer::CIRCULAR_REFERENCE_HANDLER=>function ($obj){return $obj->getId();},
            ]);

        } else {
            return $this->json([
                'message' => "No tiene permiso",
            ]);
        }

    }

Thanks!

jmcamacho7
  • 37
  • 7

1 Answers1

0

Cross-Origin Resource Sharing (CORS) is a mechanism that supports secure requests and data transfers from outside origins (domain, scheme, or port).

For example, example.com uses a text font that’s hosted on fonts.com. When visiting example.com, the user’s browser will make a request for the font from fonts.com. Because fonts.com and example.com are two different origins, this is a cross-origin request. If fonts.com allows cross-origin resource sharing to example.com, then the browser will proceed with loading the font. Otherwise, the browser will cancel the request.

CORS is blocked in modern browsers by default (in JavaScript APIs). You have to handle cors error in your backend. for this follow this link.