How to enable CORS in Slim3 framework

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.


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:

How to eanble

To enable CORS for your application:

That’s it. CORS is now enabled.

If you make a request to your app, you will notice a new header being returned:

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:

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

0 0 votes
Article Rating
Notify of
Newest Most Voted
Inline Feedbacks
View all comments
Jonathan Justo
Jonathan Justo
2 years ago

I am having errors. I posted the question on github here, any help is greatly appreciated

16 days ago

Perfect. Thank you Arjun for the help Protection Status
Would love your thoughts, please comment.x