Stanislav Lesiuk
Stanislav Lesiuk

Reputation: 15

SlimPHP - is there way to use CorsSlim with Slim v3?

I've got stuck with making a REST API with AngularJS for front and SlimPHP for backend. everuthing is OK when I use only $http.get and $http.post, but doesn't work with $http.delete and $http.put. I've set headers:

$app = new \Slim\App();

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');

but that didn't help, so I found that there's such a thing as CorsSlim, but when i write this:

require __DIR__ . '/vendor/autoload.php';

$app = new \Slim\App();

$app->add(new \CorsSlim\CorsSlim());

I immeaditely get a below problem, even after installing slim and corsslim through composer.

Fatal error: Class 'Slim\Middleware' not found in /wwwpath/vendor/palanik/corsslim/CorsSlim.php on line 5

On their CorsSlim GitHub https://github.com/palanik/CorsSlim I found that they restrict their slim to version <3.0, so it's not compatible with my Slim.

So, the question is: Are there any ways to make such a REST API with get/post/put/delete requests with Angular and Slim v3 or I have to remake the whole backend part to v2 to make it work? Thanks in advance.

Upvotes: 0

Views: 2003

Answers (2)

Kerisnarendra
Kerisnarendra

Reputation: 913

But do not forget to add the options:

$corsOptions = array(
  "origin" => "*",
  "exposeHeaders" => array("Content-Type", "X-Requested-With", "X-authentication", "X-client"),
  "allowMethods" => array('GET', 'POST', 'PUT', 'DELETE', 'OPTIONS')
);

$cors = new \CorsSlim\CorsSlim($corsOptions);

$app->add($cors);

Upvotes: 0

Davide Pastore
Davide Pastore

Reputation: 8738

Be sure to use the slim3 branch of CorsSlim:

{
  "require": {
    "palanik/corsslim": "dev-slim3"
  }
}

Then you can simply use it:

<?php
require ('./vendor/autoload.php');

$app = new \Slim\Slim();

$app->add(new \CorsSlim\CorsSlim());
?>

Upvotes: 4

Related Questions