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
How to Install
Run following composer command to install it:
How to eanble
To enable CORS for your application:
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.
I am Arjun from Hyderabad (India). I have been working as a software engineer from the last 7+ years, and it is my passion to learn new things and implement them as a practice. Aside from work, I like gardening and spending time with pets.