Angular 4 problem with Access-Control-Allow-Origin

hi
i build a angulr 4 app and back with slim
i try to send a json to the angular but i get an error in angular:
Failed to load http://localhost/products/public/: The ‘Access-Control-Allow-Origin’ header has a value ‘http://localhost/products/public/’ that is not equal to the supplied origin. Origin ‘http://localhost:4200’ is therefore not allowed access.

and i try to add that to my route but isnt work :frowning:

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

and in the browser i get the json that i want to send to angular

thanks

I haven’t worked much with Angular, but is this related perhaps? Feature request: allow CORS on local dev server

Hi,

I had same problem. I don’t know why if you add some url to Access-Control-Allow-Origin don’t work. Just add ‘*’ to get all urls work (not the best but works).

    ->withHeader('Access-Control-Allow-Origin', '*')

All code:

$app->add(function ($req, $res, $next) {
    $response = $next($req, $res);
    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, OPTIONS');
}); 

Bonus: you will be problem with OPTIONS too in Angular 4, add this to routes:

$app->options('/{routes:.+}', function ($request, $response, $args) {
    return $response;
});

Regards,

1 Like