0

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)

Matthew M
  • 331
  • 3
  • 18
  • Htaccess clearly missing `header('Content-Type: application/json');` `Access-Control-Allow-Headers: Content-Type` – Swoox Jun 07 '18 at 09:58
  • Hi Swoox, the Content-Type header is sent when completing a successful or unsuccessful request, using the `$response->withStatus(200)->withHeader("Content-Type","application/json");` So i assume you don't need it elsewhere – Matthew M Jun 07 '18 at 10:00
  • You need this in htaccess: `Access-Control-Allow-Headers: Content-Type` Don't be as stubborn as my systemmanager, I told him this 5 times and fainnly did it and got fixed. – Swoox Jun 07 '18 at 10:01
  • I've added it Swoox but still no luck, chrome is complaining about the 'Access-Control-Allow-Origin' header so i'm guessing that's where the problem is. – Matthew M Jun 07 '18 at 10:03
  • Check answer of Daan. – Swoox Jun 07 '18 at 10:04
  • Hi Swoox, I have tried Daan's response with no luck, this was one of the first results that came up in google but the 405 error is still present. I'm almost ready for quitting now! – Matthew M Jun 07 '18 at 10:16

2 Answers2

1

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

Daan
  • 11,291
  • 6
  • 26
  • 47
  • Hi Daan, i've added the following code to the response and am still getting the same error, i've also browsed the documentation and added what it states with no success still. No solution seems to work at all... – Matthew M Jun 07 '18 at 10:07
  • @MatthewM how does your stack looks like? Is it apache+modphp or nginx+php-fpm, etc... Is it behind a load balancer? Don't disable CORS, just learn how do configure the webserver correctly. You don't throw the lock out of your doors just because your key is broken. – emix Jun 07 '18 at 10:37
  • I believe it is Apache+modphp with no load balancer, i'm using MAMP to host the local version of the API which is what the app is pointing too, with default configuration. – Matthew M Jun 07 '18 at 10:39
  • Make `OPTIONS` request with curl to your API endpoint then and show us response headers. – emix Jun 07 '18 at 10:40
  • Sorry about the delay @emix, i'm not too familiar with CURL as i normally use postman, so the response for a normal put request are [the following headers](https://pastebin.com/tEfGT4MP). The options request however only contains the following headers: Accept-Ranges,Connection,Content-Length and Date. – Matthew M Jun 07 '18 at 10:56
  • Did you make an `OPTIONS` request? – emix Jun 07 '18 at 11:01
  • The options request only gave the following response headers: Accept-Ranges,Connection,Content-Length and Date – Matthew M Jun 07 '18 at 11:02
  • Thanks for your in-depth comment @emix, you are right, i have no idea how CORS works. I have read the documentation provided above and added 'The Simple Solution' code underneath the `$app = new App($config);`. I'm hoping this is the right place add this code. Thanks for your understanding. – Matthew M Jun 07 '18 at 11:08
0

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.

Matthew M
  • 331
  • 3
  • 18