SLIM 3 and CORS

Hello every body im trying to get json by an others domain (api.mysite.be)

but console debug write every time this

XMLHttpRequest cannot load http://api.anciens.loc/getnews. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://admin.anciens.loc' is therefore not allowed access.

But im using this

$api = new \Slim\App();
$cors = new \CorsSlim\CorsSlim();
$api->add($cors);
$api->get('/','HomeFct');
$api->get('/getnews','GetNewsFct');
$api->get('/authentification/{identifiant}/{motdepasse}','AuthFct');
$api->run();

AND this is the method

function GetNewsFct(Request $request,Response $reponse){
$retour = array("result"=>0);
$list = array();
$sql    = " SELECT  news_id,news_date,news_titlefr,news_titlenl,news_contentfr,news_contentnl
            FROM news
            ORDER BY news_date";
try {
    $id=42;
    $db = getDb();
    $req = $db->prepare($sql);
    //$req->bindParam("id",$id,PDO::PARAM_INT);
    $req->execute();
    $result=$req->fetchAll();
    foreach($result as $k=>$v){
        $list[] = array(    "new_id"    =>  $v['news_id'],
                            "date"      =>  $v['news_date'],
                            "titlefr"   =>  addslashes($v['news_titlefr']),
                            "text"      =>  addslashes($v['news_contentfr'])
                        );
    }
    $retour = json_encode($list);
} catch(PDOException $e) {
    $retour ='{"error":{"text":'. $e->getMessage() .'}}';
}
$reponse->getBody()->write($retour);
return $reponse;
}       

In theory it’s good no?

Im Slim noob .

Thank everybody !

You need to send in the Response a header Access-Control-Allow-Origin with the domain that will consume the route or *.
If you don’t do that always you will receive this CORS message, it’s when a domain try to get data from another domain without the knowledge of the provider.

$reponse->withAddedHeader('Access-Control-Allow-Origin', '*');

1 Like

We have documentation on this now :slight_smile:
http://www.slimframework.com/docs/cookbook/enable-cors.html