I am making a simple request to a web service that I have hosted on a hosting. If I try with postman, it returns a 200 and everything works fine, but I don't know what I'm doing wrong in my example. I leave you the code:
$(document).ready(function(){
var url = 'https://www.dominiowebservice.com/miws/'
var jsonData = {
"id": 23,
"datos": {
"nombre": "Nombre",
"email": "[email protected]",
"comentario": "Texto de mi comentario"
}
}
$.ajax({
type: 'POST',
url: url,
data: jsonData,
dataType: 'json',
contentType: 'application/json',
headers: { "Authorization": 'Bearer ' + 'lzoKSJorIm0rJEfTcsw'},
success: function(response) {
console.log('SUCCESS')
console.log(response)
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
It returns the following error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.dominiowebservice.com/miws/. (Reason: CORS preflight channel did not succeed).
How can I solve that? Is the error in my ajax request or in the web service itself? But I'm telling you that since Postman it has worked for me
CORS (also known as cross-origin resource sharing ) rules prevent you from accessing resources from an external page if the external page does not authorize your website to do so.
By default, all queries within the same origin (same URL or Same Origin Policy ) are assumed to be secure and do not use CORS for validation, only queries to external origins (or URLs).
To do this, the browser makes a previous query (preflight request) using the HTTP method
OPTIONS
.Precisely that previous test is the one that has failed and that is why it generates the error:
Or, what is the same, that the previous verification that your API allows queries from the origin has failed and, therefore, it is assumed that it is prohibited.
One way to implement the response to that previous query could be by adding the following code to the beginning of your PHP script:
NOTE : This code allows access to your API from any URL .
If you want to restrict API access to a small number of URLs then you should do something like the following:
There are many HTTP headers that allow us to manage data exchange:
Among them, an important one, in terms of performance, is
Access-Control-Max-Age
. It allows us to allow the browser to save the result of the previous query in cache for a certain time:The only way to avoid the same origin policy on ajax calls is to use the jsonp data type. However, the server must support it.
Here is a rather interesting article on the subject. It talks about the same origin policy and the problems with ajax. Description and examples of json, when it can be used, and problems of using it (mainly security).