How to solve ‘CORS policy: No ‘Access-Control-Allow-Origin’ header’?

The issue is because the Same Origin Policy is preventing the response from being received due to the originating/receiving domains being different due to the port numbers. To fix this you’ll need to return CORS headers in the response from localhost. You can resolve this issue using include headers in AJAX, .htaccess file.

Using Header in AJAX

Add headers in your AJAX request

$.ajax({
	method: 'POST',
	url: 'http://your-server-url',
	headers: {
		'Access-Control-Allow-Origin':'*',
		'Access-Control-Allow-Methods': 'GET, POST, OPTIONS, PUT, DELETE',
		'Access-Control-Allow-Headers':'Origin, X-Requested-With, Content-Type, Accept, API-Key, Authorization, X-Test'
	},
	data: {name:"jhon"},
	success: function(response){
		console.log(response);
	}
});

Using Headers in .htaccess file

Add this code in your htaccess file

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
    Header set Access-Control-Allow-Methods "GET, POST, OPTIONS, PUT, DELETE"
    Header set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept, API-Key, Authorization, X-Test"
</IfModule>

Leave a Reply

Your email address will not be published. Required fields are marked *