CORS policy: It does not have HTTP ok status

From https://example.com, I would like to get data from https://api.example.com/login. But what I get is this error:

Access to XMLHttpRequest at ‘https://api.example.com/login‘ from
origin ‘https://example.com‘ has been blocked by CORS policy: Response
to preflight request doesn’t pass access control check: It does not
have HTTP ok status.

This is how I try to get the data:

public signIn(data): Observable<number> {
  return this.http.post<number>(environment.apiBaseUrl + '/login', data);
}

And this is how I try to send the data:

/**
 * @Route("/login", methods={"POST"})
 * @param Request $request
 * @return Response
 */
public function login(Request $request) {
    $data = json_decode($request->getContent(), true);
    $isLoggedIn = $this->loginService->login($data);
    return ($isLoggedIn) ? new Response(1) : new Response(0);
}

The .htaccess of my API (Symfony4 framework), which is on api.example.com, looks like this:

Header set 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"

<IfModule mod_rewrite.c>    
    RewriteEngine On

    # Determine the RewriteBase automatically and set it as environment variable.
    RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::$
    RewriteRule ^(.*) - [E=BASE:%1]

    # If the requested filename exists, simply serve it.
    # We only want to let Apache serve files and not directories.
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule .? - [L]

    # Rewrite all other queries to the front controller.
    RewriteRule .? %{ENV:BASE}/index.php [L]
</IfModule>

Why do I get this error?

Update

This is how the headers look like in Google Chrome:

enter image description here

The weird thing is that the status of get-cookie (which is from the same URL) is 200. This is how its code looks like:

/**
 * @Route("/login/get-cookie", methods={"POST"})
 * @param Request $request
 * @return Response
 */
public function getCookie(Request $request) {
    $cookie = json_encode($this->loginService->getCookie($request->getContent()));
    return new Response($cookie);
}

The only difference that I see is that set-cookie will get called whenever the page gets loaded but to get the response of login, a form needs to be submitted.

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *