Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access-Control-Origin within Slim Framework and Ember.js

Tags:

php

ember.js

slim

After reading many questions/answers I decided to post. I think Slim Framework - jQuery $.ajax request - Method DELETE is not allowed by Access-Control-Allow-Methods sums up most of the information I've found and tried out.

I'm using MAMP with PHP 5.6 for development but the production environment will most probably be a shared host. I'm also using ember.js

When ember does a POST request I get the Access-Cross-Origin message:

XMLHttpRequest cannot load http://foo.bar/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

I understand that settings the appropriate headers on the server would solve the issue but I do not know when to do it. What I currently do in the Slim framework is:

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

$app->options('/(:name+)', function() use($app) {                  
    $response = $app->response();
    $app->response()->status(200);
    $response->header('Access-Control-Allow-Origin', '*'); 
    $response->header('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With, X-authentication, X-client');
    $response->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
 });

However, I've checked Ember.js requests and it is not requesting OPTIONS and thus the correct headers are not set.

If I set the headers in an individual route of Slim then it works correctly. But I do not want to set the headers on each route, one by one.

What can I do to set the headers for all routes?

like image 569
jrlainfiesta Avatar asked Mar 30 '15 02:03

jrlainfiesta


2 Answers

Instead of adding a new package to your project you could just do this

$app->add(function ($req, $res, $next) {
    $response = $next($req, $res);
    return $response
            ->withHeader('Access-Control-Allow-Origin', 'http://mysite')
            ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
            ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
}); 

https://www.slimframework.com/docs/v3/cookbook/enable-cors.html

like image 68
Thomas Valadez Avatar answered Oct 14 '22 13:10

Thomas Valadez


CorsSlim is your friend:

<?php
$app = new \Slim\Slim();
$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);
like image 43
Davide Pastore Avatar answered Oct 14 '22 13:10

Davide Pastore