I know this question has been asked tons of times in SO
but this problem is totally different!
As Mozilla
itself says about the header, you have to set this like below in nginX
:
add_header 'Access-Control-Allow-Origin' 'origin-list'
I have set the CORS
options and the interesting part is that preflight request
succeeds:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Origin,Content-Type,Accept,authorization,Expires,Pragma,x-custom-header
Access-Control-Allow-Methods: GET, POST, OPTIONS, PATCH
Access-Control-Allow-Origin: https://localhost:3000
The endpoint is /user
. Now the actual GET
request is sent to server and again it succeeds with 200
response code JSON
payload it expected!
The problem resides in the part that I want to get this data from within jQuery
like below:
$.ajax({
type: "GET",
url: url_endpoint,
beforeSend: function(request) {
request.setRequestHeader("Authorization", "Bearer " + _TOKEN);
},
dataType: "json",
error: function (data, stat) {
console.log('got error data: ', stat);
console.log(data);
},
complete: function(xhr, data) {
console.log('here is the data...', data, xhr);
}
}).catch(function(data,x,y) {
console.log(data,x,y,'it seems request has error!!!!');
});
It logs the error parts of the request like inside of catch
and in console I see the below error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.example.com/restapi/user . (Reason: CORS header 'Access-Control-Allow-Origin' missing).[Learn More]
It displays that the header is missing while I explain that headers are returned in OPTIONS
. To make sure this error relates to this specific request I commented out the /user
request and error of CORS
gone.
Why I get CORS
while server response 204 for OPTIONS
and why I get CORS
while json response is returned for /user
The CORS headers must also accompany the response to the GET
, not just the response to the OPTIONS
. Eg, you send them twice (if there's a preflight).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.