jQuery ajax working but axios giving CORS error - javascript

I am moving my project from jQuery to axios. It is working fine in other places but I am getting error in one specific place. axios is giving CORS error but jquery working fine. Here is the code:
jQuery
$.ajax({
url: 'my-url-here',
type: 'post',
data: JSON.stringify({
"attachmentNames": [ "filename.pdf" ]
}),
success: function (data) {
console.info(data);
}
});
axios
axios({
url: 'my-url-here',
method: 'post',
data: {
"attachmentNames": [ "filename.pdf" ]
}
}).then(function(resp) {
console.log(resp);
});

Browsers will send a preflight request if you send a Content-Type with a value that isn't on a very short list.
application/json will trigger a preflight.
Axios will, by default, encode data as JSON and say it is sending JSON.
In your jQuery, you are manually encoding the data as JSON and failing to set the correct Content-Type header. As a result you are lying to the server and claiming the data is application/x-www-form-urlencoded (the default for jQuery). This header doesn't need a preflight request.
Configure the server to respond to a preflight request with permission (in Access-Control-Allow-Headers) to change the Content-Type.

Related

Cross-domain POST doesn't work with Angular HttpClient but works with jQuery

I am migrating to Angular 13 and I want to use HttpClient instead of jQuery.ajax.
The following jquery code works:
function asyncAjax(url: any){
return new Promise(function(resolve, reject) {
$.ajax({
type: 'POST',
crossDomain: true,
xhrFields: {
withCredentials: true
},
url: url,
data: null,
contentType: "text/plain; charset=utf-8",
dataType: "json",
success: function(data) {
resolve(data) // Resolve promise and when success
},
error: function(err) {
reject(err) // Reject the promise and go to catch()
}
});
});
}
...
const json: any = await asyncAjax(url);
However, when I do with HttpClient:
private readonly _httpClient: HttpClient;
constructor(httpClient: HttpClient) {
this._httpClient = httpClient;
}
...
const headers = new HttpHeaders({'Content-Type':'application/json; charset=utf-8'});
const json = await firstValueFrom(this._httpClient.post<T[]>(url, null,
{ headers: headers, withCredentials: true}));
I get:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at [url]. (Reason: CORS request external redirect not allowed).
Could anyone say how to make it work with HttpClient?
In your jQuery code you are sending no data at all and claiming you are sending plain text.
data: null,
contentType: "text/plain; charset=utf-8",
In your Angular code you still aren't sending any data, but this time you are claiming you are sending JSON.
const headers = new HttpHeaders({'Content-Type':'application/json; charset=utf-8'});
JSON isn't a data type supported by HTML forms which means to send it on a cross-origin request the browser will send a preflight request.
The server isn't granting permission using CORS in its response to that preflight request and seems to be issuing a redirect instead.
The quick and dirty solution here is to send the same Content-Type header as you were when the code worked.
The better solution is to consider your API design. Why are you using a POST request but not POSTing any data in the first place? Possibly this should be a GET or DELETE request instead.
It is also possible that the cause of the redirect is that the value of url has changed (maybe from http://example.com/foo/ to http://example.com/foo) and that needs to be corrected.

Response for preflight has invalid HTTP status code 400 using Axios

I'm using Axios library to make an API call in my React application.I call the API and then populate a table using React.
My Axios call is as follows:
axios({
method: 'get',
url: DataURL,
headers: {
'Content-Type' : 'application/json',
'Id': user.Id,
'Name' : user.Name,
'api-token' : user.access_token,
'clientId' : 'web',
},
responseType: 'json',
})
.then((response) => {
this.setState({ tableData: response.data });
});
However I get this error:
XMLHttpRequest cannot load MY API URL Response for preflight has invalid HTTP status code 400
The same was working in my dev environment where I wasn't adding any headers, however after migrating to new env which required me to add headers, Im getting the above error.
My question is, is this a client side issue(like wrong header format etc) or is it something to do with server side handling of the API call?
I think this is a server-side issue. If you are using node in the background you need CORS as a middleware (https://www.npmjs.com/package/cors).
For other server solutions there are of course also cors request handler.

How to send client side cookies (javascript) to server side (node.js) using Microsoft Bot Framework Directline API? [duplicate]

I am working on an internal web application at work. In IE10 the requests work fine, but in Chrome all the AJAX requests (which there are many) are sent using OPTIONS instead of whatever defined method I give it. Technically my requests are "cross domain." The site is served on localhost:6120 and the service I'm making AJAX requests to is on 57124. This closed jquery bug defines the issue, but not a real fix.
What can I do to use the proper http method in ajax requests?
Edit:
This is in the document load of every page:
jQuery.support.cors = true;
And every AJAX is built similarly:
var url = 'http://localhost:57124/My/Rest/Call';
$.ajax({
url: url,
dataType: "json",
data: json,
async: true,
cache: false,
timeout: 30000,
headers: { "x-li-format": "json", "X-UserName": userName },
success: function (data) {
// my success stuff
},
error: function (request, status, error) {
// my error stuff
},
type: "POST"
});
Chrome is preflighting the request to look for CORS headers. If the request is acceptable, it will then send the real request. If you're doing this cross-domain, you will simply have to deal with it or else find a way to make the request non-cross-domain. This is why the jQuery bug was closed as won't-fix. This is by design.
Unlike simple requests (discussed above), "preflighted" requests first
send an HTTP request by the OPTIONS method to the resource on the
other domain, in order to determine whether the actual request is safe
to send. Cross-site requests are preflighted like this since they may
have implications to user data. In particular, a request is
preflighted if:
It uses methods other than GET, HEAD or POST. Also, if POST is used to send request data with a Content-Type other than
application/x-www-form-urlencoded, multipart/form-data, or text/plain,
e.g. if the POST request sends an XML payload to the server using
application/xml or text/xml, then the request is preflighted.
It sets custom headers in the request (e.g. the request uses a header such as X-PINGOTHER)
Based on the fact that the request isn't sent on the default port 80/443 this Ajax call is automatically considered a cross-origin resource (CORS) request, which in other words means that the request automatically issues an OPTIONS request which checks for CORS headers on the server's/servlet's side.
This happens even if you set
crossOrigin: false;
or even if you ommit it.
The reason is simply that localhost != localhost:57124. Try sending it only to localhost without the port - it will fail, because the requested target won't be reachable, however notice that if the domain names are equal the request is sent without the OPTIONS request before POST.
I agree with Kevin B, the bug report says it all. It sounds like you are trying to make cross-domain ajax calls. If you're not familiar with the same origin policy you can start here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Same_origin_policy_for_JavaScript.
If this is not intended to be a cross-domain ajax call, try making your target url relative and see if the problem goes away. If you're really desperate look into the JSONP, but beware, mayhem lurks. There really isn't much more we can do to help you.
If it is possible pass the params through regular GET/POST with a different name and let your server side code handles it.
I had a similar issue with my own proxy to bypass CORS and I got the same error of POST->OPTION in Chrome. It was the Authorization header in my case ("x-li-format" and "X-UserName" here in your case.) I ended up passing it in a dummy format (e.g. AuthorizatinJack in GET) and I changed the code for my proxy to turn that into a header when making the call to the destination. Here it is in PHP:
if (isset($_GET['AuthorizationJack'])) {
$request_headers[] = "Authorization: Basic ".$_GET['AuthorizationJack'];
}
In my case I'm calling an API hosted by AWS (API Gateway). The error happened when I tried to call the API from a domain other than the API own domain. Since I'm the API owner I enabled CORS for the test environment, as described in the Amazon Documentation.
In production this error will not happen, since the request and the api will be in the same domain.
I hope it helps!
As answered by #Dark Falcon, I simply dealt with it.
In my case, I am using node.js server, and creating a session if it does not exist. Since the OPTIONS method does not have the session details in it, it ended up creating a new session for every POST method request.
So in my app routine to create-session-if-not-exist, I just added a check to see if method is OPTIONS, and if so, just skip session creating part:
app.use(function(req, res, next) {
if (req.method !== "OPTIONS") {
if (req.session && req.session.id) {
// Session exists
next();
}else{
// Create session
next();
}
} else {
// If request method is OPTIONS, just skip this part and move to the next method.
next();
}
}
"preflighted" requests first send an HTTP request by the OPTIONS method to the resource on the other domain, in order to determine whether the actual request is safe to send. Cross-site requests
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Consider using axios
axios.get( url,
{ headers: {"Content-Type": "application/json"} } ).then( res => {
if(res.data.error) {
} else {
doAnything( res.data )
}
}).catch(function (error) {
doAnythingError(error)
});
I had this issue using fetch and axios worked perfectly.
I've encountered a very similar issue. I spent almost half a day to understand why everything works correctly in Firefox and fails in Chrome. In my case it was because of duplicated (or maybe mistyped) fields in my request header.
Use fetch instead of XHR,then the request will not be prelighted even it's cross-domained.
$.ajax({
url: '###',
contentType: 'text/plain; charset=utf-8',
async: false,
xhrFields: {
withCredentials: true,
crossDomain: true,
Authorization: "Bearer ...."
},
method: 'POST',
data: JSON.stringify( request ),
success: function (data) {
console.log(data);
}
});
the contentType: 'text/plain; charset=utf-8', or just contentType: 'text/plain', works for me!
regards!!

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

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