RKD RKD - 7 months ago 51
Javascript Question

Slim Framework v3 api call from angularjs $http

I have been struggling with this issue from past few days.

I have created api using slim framework v3 in php.

and when i call any route from angularjs $http i get console error as:-

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

use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

require 'vendor/autoload.php';
require 'app/config/configuration.php';

$app = new Slim\App(["settings" => $config]);
spl_autoload_register(function ($class_name) {
require("app/" . $class_name . ".php");

$app->get("/testing",function(Request $request,Response $response){
function generateResponse($response, $data)
return $response->withStatus(200)
->withHeader("Content-Type", "application/json")
->withHeader("Access-Control-Allow-Origin", "*")
->withHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
->withHeader("Access-Control-Allow-Headers", "Content-Type, Depth, User-Agent, X-File-Size,X-Requested-With, If-Modified-Since,X-File-Name, Cache-Control, x-hash-key, x-req-timestamp, user-language-pref, Content_Language")


I have added headers in response. But still when i call testing route api from $http it throws error.

Am totally blank i know am just missing something silly. Please help me out to solve this thing.



By adding header in php file it is working now.
header('Access-Control-Allow-Origin: *');

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

Please note this link it might be handy some days:-
Click to go->


One thing is that there's missing return on line 14:

return generateResponse($response,array("message"=>"success"));

You can check whether the headers are present in the response in the browser's dev console.

From a quick review this seems as the only issue.