When you are working with API’s most of the time you are facing the Cros Policy issue due to different reason. Right? Every time you find the solution on google and stack overflow. But now you don’t need to go anywhere in this article you will find the proper solution. So without wasting much time in the introduction lets start the solution.
1 Solution: Install the Allow-Control-Allow-Origin plugin:
You can install the chrome extension to solve this issue but this issue is fixed on your local machine, hit the API by local IP like localhost then this is the best solution. You can make is to install the moesif CORS extension . Once installed, click it in your browser to activate the extension.
This plugin allows you to send cross-domain requests directly from the browser without receiving Cross-Origin Errors.
You can override the Request Origin header with this plugin and also have Access-Control-Allow-Origin set to *.
Note : It's not a good solution if you are working on a live server but if you are working on the local machine
2 Solution: Access-Control-Allow-Origin code in .htaccess file
The Access-Control-Allow-Origin response header indicates whether the response can be shared with requesting code from the given domain. you can control this issue by the backend address that the web app’s API requests are going to.
you can add the code in the root of your server in .htaccess file
//Allow code from any origin to access <IfModule mod_headers.c> Header set Access-Control-Allow-OriginAccess-Control-Allow-Origin "*" </IfModule> //Allow requesting code from the origin-specific domain <IfModule mod_headers.c> Header set Access-Control-Allow-Origin : https://yourdomain.com </IfModule>
3 Solution: Set Access-Control-Allow-Origin with PHP file
You can add the below code on your root index.php file or any header.php file.
//Allow code from any origin and headers to access header("Access-Control-Allow-Origin: *"); ///Allow requesting code from the origin-specific domain header('Access-Control-Allow-Origin: http://yourdomain.com', false);
Note: if you add star * it means you allow everyone to use your API's data so it's better you will only allow the website domain name in which you want to work. It will make your data secure
4 Solution: Cross Browser Protocol
If there is cross-browser issue due to HTTP and HTTPS in the API. The API URL’s make sure you use the same HTTP protocol. If your site is hosted with SSL means your domain name started with https then you need to use the same protocol for receiving and sending data API endpoint.
For more detail, you can visit this website Click Here