Response for preflight has invalid HTTP status code 400 - javascript

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.

Related

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.

CORS Error:Response to preflight request doesn't pass access control check when trying to access Azure Search Api

I am using an ajax put request to perform a merge operation to update a field named DocType for a particular document in azure search index. But getting the error: Failed to load resource: the server responded with a status of 404 (Not Found)
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
The ajax request I am performing:
var jsonMeta = {
"value": [
{
"#search.action": "merge",
"metadata_storage_path": "*******jkio********",
"DocType": "Test_Merge"
}
]
};
var jsonString = JSON.stringify(jsonMeta);
var url = "https://documentsmartdetect.search.windows.net/indexes/document-smartdetect-index/docs/index?api-version=2017-11-11";
$.ajax({
url: url,
method: 'PUT',
data: JSON.stringify(jsonMeta),
// This is the important part
xhrFields: {
withCredentials: true
},
crossDomain: true,
contentType: 'application/json',
headers: {
"api-key": "***************89**",
},
success: function (response) {
},
error: function (xhr, status) {
alert('error');
}
});
I have also tried using Allowed origin type : all on the azure portal. Need some assistance to fix the CORS issue.
Azure Search does not allow calls from front-end JavaScript, so you cannot do what you want directly.
You will have to call Azure Search from a back-end.
This is actually a serious security problem as well since your Search key is now public within the JavaScript that is sent to all visitors of your web app.

Request header values not send? CORS - jQuery Ajax

Im trying to make a request from one application to another. So i created some headers which are required by my application and filled them in for the Ajax Request. Here is my code:
$.ajax({
method: 'GET',
url: 'http://my-domain.com/apps/filters/get-filters',
beforeSend: function(request){
request.setRequestHeader("X-Webshop-Domain", window.location.host);
request.setRequestHeader("X-Language", $('html').attr('lang'));
request.setRequestHeader("X-Request-Protocol", window.location.protocol);
request.setRequestHeader("X-Api-Version", '2');
},
headers: {
"X-Webshop-Domain": window.location.host,
"X-Language": $('html').attr('lang'),
"X-Request-Protocol": window.location.protocol,
"X-Api-Version": '2',
},
data: {}, success: function ( response )
{
}
});
Now when i load a page, this method is called but no response given. It gives me the "Header not allowed" issue. But when i check in my network tab (developer tools Chrome) i see my request, i see some headers but none of those. Does anybody has a idea how this is possible or what im doing wrong?
In case of CORS (cross domain requests), only basic headers are allowed. You will need to add the headers you wish to send to the server's response header:
Access-Control-Allow-Headers: X-Webshop-Domain, ...
Here's a related question you may find useful: Ajax Request header field Key is not allowed by Access-Control-Allow-Headers

CORS request with Ajax/Javascript/Django

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.

CORS issue while submitting data to google forms in angular

While submitting the data :
Error Message : XMLHttpRequest cannot load https://docs.google.com/forms/d/xxxxxxxxxxxxx/formResponse. 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:8090' is therefore not allowed access. The response had HTTP status code 405.
$scope.postDataToGoogle = function(){
$http({
method: 'POST',
crossDomain: true,
url: 'https://docs.google.com/forms/d/XXXXXXXXXXXXXXXXXXXXXXXX/formResponse',
// dataType: "xml",
data: tempData,
}).success(function(data,status){
//alert(data)
console.log("Success");
}).error(function(data,status) {
console.log('Error:' + status);
});
}
Its not about jquery or angular, CORS allows or disallow done by Back-end server.
Google might not support this.(to access https://docs.google.com)
CORS (Cross-Domain Resource Sharing) allows you to more cleanly separate your front-end from your back-end.
CORS is a group of special response headers sent from the server that tell a browser whether or not to allow the request to go through
Access-Control-Allow-Origin: http://example.com.
Why does jQuery throw an error when I request external resources using an Appcache Manifest?
I do have tried with angular still not able solve it, but with jQuery its works for me.
$.ajax({
url: 'https://docs.google.com/forms/d/xxxxxxxxx',
data: tempData,
type: "POST",
dataType: "xml",
statusCode: {
0: function () {
alert('error');
},
200: function () {
alert('Thank you for your valuable feedback');
}
}
})

Categories

Resources