CORS request with Ajax/Javascript/Django - javascript

I wanna make a CORS get request to, say google (just an example. I'm actually accessing a website that returns json data). Below is my ajax code:
$.ajax({
url: "https://www.google.com",
type: "get",
dataType: "json",
crossDomain: true,
success: function(data, textStatus) {
alert ("success" + data);
},
error: function(data, textStatus) {
alert ("fail" + data);
}
})
With the above code I got this error:
XMLHttpRequest cannot load https://www.google.com/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://sdlweb-dev:1234' is therefore not allowed access. The response had HTTP status code 405.
I tried adding code like
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "X-Requested-With,content-type",
"Access-Control-Allow-Credentials": true
}
but still got the same error.
I tried changing dataType from 'json' to 'jsonp'. This way the request is sent, but since the response isn't jsonp, I got another error:
Uncaught SyntaxError: Unexpected token <
Without modifying the server side (I mean the url that I send get request to, because I do not have access to that), can I be able to send CORS request?
Any help is appreciated!!!
Thanks,
Fei

You must have access to the server code in order to allow CORS requests.
The headers that you showed should be headers sent back in the response, not in the request.

Related

CORS issue when trying POST

I am getting a CORS issue when trying to use POST with my API.
Access to XMLHttpRequest at 'http://localhost/finalMandatory/api/track/create.php' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
I've tried to follow some other posts that seems to have the same issue, but I'm having a hard time implementing it in my own code.
$.ajax({
url: "http://localhost/finalMandatory/api/track/create.php",
type : "POST",
contentType : 'application/json',
data : form_data,
success : function(result) {
showProducts();
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
console.log(form_data);
}
});
I'm also using these headers in my api, which i thought would be enough to deal with CORS problems.
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
I hope someone can help me fix my issue.
I guess that the OPTION request sent to create.php is failing. Maybe because your backend code is trying to perform the action even in this case. OPTION requests should terminate only with CORS headers and an empty body. You can check this with a REST client (Postman for example).

Problem calling an API that requires a key in header, using JS and Ajax

Since I want to display the result of an API call in a HTML page, I used Ajax in a Javascript to get the information from the API.
The DEV API does not require a key, and I have been able to get the result (yeah!)
$.ajax({
url: "https://api-dev.XXXXXXXXX.com/enterprise/123456/treeCount/2020-05",
async: false,
success: function(result){
totalCount = totalCount + result.count;
}
}),
So this code above works fine.
The Prod API requires a key in the header though, and I can't make it work. Found lots of example in StackOverflow, but all my tests failed.
$.ajax({
url: "https://api.XXXXXXXXX.com/enterprise/123456/treeCount/2019-12",
headers: { "x-api-key" : "12345678910" },
async: false,
success: function(result){
totalCount = totalCount + result.count;
}
})
It works well in Postman when adding x-api-key with the value of the key, so I know that the key is good
Any idea what I'm doing wrong?
Thanks!
EDIT February 15th:
Thanks for your answers. Went in the console, saw some CORS error, and then I added some information related to CORS and to Content-Type, so my new code in the JavaScript is the following:
$.ajax({
url: "https://api.XXXXXXXXXX.com/enterprise/123456/treeCount/2019-12",
headers: { "x-api-key" : "12345678910",
"Content-Type" : "application/json",
'Access-Control-Allow-Origin': '*' },
async: false,
success: function(result){
totalCount = totalCount + result.count;
}
})
Still get the same error message though:
jquery-3.3.1.min.js:2 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
jquery-3.3.1.min.js:2 Access to XMLHttpRequest at 'https://api.XXXXXXXXX.com/enterprise/123456/treeCount/2020-05' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
jquery-3.3.1.min.js:2 Failed to load resource: net::ERR_FAILED
When In only do the call on the Dev API (who does not require an API key), it works fine as indicated above, and I do not get the CORS error.
Again, thanks for your help.

POST gets converted to GET, when sending request via local apache

I am trying to send a post request with the following code. But the request goes as GET request, instead of POST. How to fix this.
$.ajax({
url: 'https://www.exampleurl.com',
method: 'POST',
headers: {"Access-Control-Allow-Origin": true},
data: {url:'bla',call:"trans"}
dataType: 'jsonp',
success: function(data){
console.log('succes: '+data);
}
});
This is the error I am getting
XMLHttpRequest cannot load https://example.com. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 401.
When removed the header Access-Control-Allow-Origin, I am getting a 404 error
I don't think, you can use a POST method with jsonp request. jsonp callbacks only for with GET method. Have a look at link .
You don't have to pass parameters in url attribute when you want to send POST request you should use data attribute instead, take a look at jQuery.ajax() :
$.ajax({
url: 'https://www.exampleurl.com',
method: 'POST',
data: {q:1, q2:2},
headers: {"Access-Control-Allow-Origin": true},
dataType: 'jsonp',
success: function(data){
console.log('succes: '+data);
}
});
Hope this helps.

$.ajax -- put method, sending OPTIONS

I have the following code:
function test(segmentId) {
var url = "http://...../api/avoidsegments/123456";
$.ajax({
url: url,
type: "PUT",
contentType: "application/json",
data : {
"appID": ig_appID,
"clientCode": ig_clientCode,
"segmentID": segmentId
},
success: function(output) {
console.log(output);
},
error: function(err) {
console.log('error: ', err);
}
});
}
I'm getting the following response:
OPTIONS http://...../api/avoidsegments/123456 401 (Unauthorized)
(index):1 XMLHttpRequest cannot load http://...../api/avoidsegments/123456.
Response for preflight has invalid HTTP status code 401
How do I fix this, and send a put request? Thanks.
You are trying to do Cross Origin HTTP Request (CORS). Solution is to enable CORS on your server side and as i can see u got 401 unauthorized so send Authorization header with requests (i dont know your authorization implementation).

Response for preflight has invalid HTTP status code 400

I'm trying to make a REST call (POST) using AJAX. This is my AJAX code
<script>
var settings = {
"async": true,
"crossDomain": true,
"dataType": "json",
"url": "http://localhost:port/service/myservice",
"method": "POST",
"data": '{jsondata}',
"headers": {
"accept": "application/json",
"Authorization": "authValue"
}
}
$.ajax(settings)
.done(function (response) {
console.log(response);
});
</script>
Initially I got this error: XMLHttpRequest cannot load http://localhost:port/service/myservice. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 400.
To resolve this issue I added the following code in my dropwizard application
Dynamic filter = env.servlets().addFilter("CORS", CrossOriginFilter.class);
filter.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,PUT,POST,DELETE,OPTIONS");
filter.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*");
filter.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*");
filter.setInitParameter("allowedHeaders", "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin");
filter.setInitParameter("allowCredentials", "true");
filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
After adding this my initial exception went away, but I'm getting the following exception: XMLHttpRequest cannot load http://localhost:port/service/myservice. Response for preflight has invalid HTTP status code 400
Is this issue related to CORS? What am I doing wrong here?
UPDATE
After doing more debugging I found this behavior. When sending the request without the Authorization header I'm getting 415 (Unsupported Media Type) error.
I think something wrong with my AJAX code, can someone please help me find the issue? Thanks.
You may try here mentioned as complete answer in this thread.
$.ajax({
type:"POST",
beforeSend: function (request)
{
request.setRequestHeader("Authority", authValue);
},
url: "http://localhost:port/service/myservice",
data: "json=" + escape(JSON.stringify(createRequestObject)),
processData: false,
success: function(msg) {
$("#results").append("The result =" + StringifyPretty(msg));
}
});
try to add the following to your settings?
xhrFields: { withCredentials: true }
if you need to pass JSON data in the AJAX call, you need to specify content-type as json/application, so the server knows you are trying to send JSON data. But that will change the default content-type of the call and the call will qualify for pre-flight checking, which need proper CORS enabled client & server request.
For easier use case, do not use JSON.stringify() when you pass data, just make a simple string with {key:value, key:value, ...} format, and pass the string as the data. The Ajax call serializes the data by default and does the right thing, and the call stays as a single POST call to the server, where as the pre-flight mode is two calls.

Categories

Resources