Matthew M
Matthew M

Reputation: 381

Disable CORS due to problematic 405 errors

The background:

I have a slim based API created and currently running at a local domain, e.g localhost/api

I have a mobile app using the ionic framework (based off of angular) and have the following code using the httpClient as http:

let accessurl = this.general.apiURL + '/v2/update/status/' + this.machineToChange;
    const headers = new HttpHeaders()
      .set('Authorization', 'Bearer: ' + this.general.apiKey);
    this.http.put(accessurl, {
      statusFuelled: 1
    }, { headers: headers }).subscribe(result => {
      console.log(JSON.stringify(result));
    }, err => {
      console.log(JSON.stringify(err));
    });

I have tried every stack overflow question i could find to let the slim framework disable cors, here is just a few:

$app->options('/update/status/{machineNo}', function ($request, $response) {
  header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
  header('Access-Control-Allow-Credentials: true');
  header('Access-Control-Max-Age: 86400');    // cache for 1 day
  return $response->withStatus(200);
});

Or:

//http://stackoverflow.com/questions/18382740/cors-not-working-php
  if (isset($_SERVER['HTTP_ORIGIN'])) {
      header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
      header('Access-Control-Allow-Credentials: true');
      header('Access-Control-Max-Age: 86400');    // cache for 1 day
  }

  // Access-Control headers are received during OPTIONS requests
  if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

      if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
          header("Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS");

      if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
          header("Access-Control-Allow-Headers:        {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

      exit(0);
  }

Or:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header('Content-Type: application/json');

Or in .HTACCESS:

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
Header add Access-Control-Allow-Headers: Content-Type

And many more middlewares using composer.

I have also ran the code from the Slim Website with no success.

Non have worked, and it is causing me so much trouble, so i just want CORS disabled permanently as it is doing way more harm than good.

I have no idea where the issue is being caused by, a wrong httpClient request or CORS being a pain like normal.

If anyone could help, please let me know.

I'm running PHP 5.6 due to server restrictions, so middlewares like tuupola/cors won't work due to being PHP <7

Some errors:

Safari Throws: Failed to load resource: Preflight response is not successful

Chrome Throws: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 405.

Chrome also Throws: OPTIONS http://localhost/api/v2/update/status/{ID} 405 (Method Not Allowed)

Upvotes: 0

Views: 1027

Answers (2)

Matthew M
Matthew M

Reputation: 381

CodeKit was the issue for CORS not working. When running directly through MAMP all the requests came back properly, however when sending the same request through the CodeKit server, the CORS Middleware didn't work.

I believe Daan's response is more appropriate for others having this issue however, so will mark that one as correct.

Upvotes: 0

Daan
Daan

Reputation: 12236

Send the header with the response:

return $response
        ->withHeader('Access-Control-Allow-Origin', '*')
        ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
        ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');

See also the slim documentation: https://www.slimframework.com/docs/v3/cookbook/enable-cors.html

Upvotes: 1

Related Questions