In this post, you will learn about Cross-Origin Resource Sharing. Http requests are restricted by the same-origin policy, which means where scripts can be loaded from the same Origin. Specifically, the protocol, domain, and port must match. It means you can’t send the request to other origins, this restriction is there for a security reason, it will prevent the attacks.
When you send a Cross-Origin request you will get errors similar to the below shown.
Chrome:
XMLHttpRequest cannot load http://localhost:3000. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Firefox:
Cross-Origin Request Blocked: The Same Origin Policy disallows How to enable CORS in Express.js s reading the remote resource at http://localhost:3000. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
How to implement CORS
CORS
is implemented through the Access-Control-Allow-Origin
header. The easiest way to implement it in an Slim 3 application is to use the cors-middleware
package.
How to Install
Run following composer command to install it:
$ composer require tuupola/cors-middleware
How to eanble
To enable CORS for your application:
$app->add(new Tuupola\Middleware\CorsMiddleware);
That’s it. CORS
is now enabled.
If you make a request to your app, you will notice a new header being returned:
Access-Control-Allow-Origin: *
The Access-Control-Allow-Origin header determines which origins are allowed to access server resources over CORS (the * wildcard allows access from any origin).
Restricting only to allowed hosts
If you want to restrict AJAX access to the specific origins, you can use the origin option:
$app->add(new Tuupola\Middleware\CorsMiddleware([ "origin" => ["arjunphp.com","localhost"], "methods" => ["GET", "POST", "PUT", "PATCH", "DELETE"], "headers.allow" => [], "headers.expose" => [], "credentials" => false, "cache" => 0, ]));