I'm using axios in my application, but I'm having a hard time setting the content of the request.
There's currently a call to a URL using $.ajax like this:
$.ajax({
method: 'POST',
data: { 'accountId': accountId },
url: serverUrl,
/* success: ... */
});
And when I look at this request in Chrome dev tools, at the end I see something like this:
Now, I'm trying to do the same thing with axios:
axios.post(serverUrl, { accountId: accountId })
.then(/* ... */);
But, when I look at the request in Chrome dev tools, I have this:
How can I get axios to do the same formatting as jQuery? And maybe the question is that: are they different or it's just the representation?
Also, I noticed that the jQuery call is somehow adding this header: x-requested-with: XMLHttpRequest, but to have the same header in axios, I have to set it manually. Is it normal? Am I missing an axios configuration to add this header?
Thank you
Some frameworks use this header to detect XHR requests, for example. Grails Spring uses this header to identify the query XHR and gives the JSON response or the HTML response as a response.
Most Ajax libraries (Prototype, JQuery and Dojo from version 2.1) include the X-Requested-With header, which indicates that the query was made using XMLHttpRequest instead of running by clicking a regular hyperlink or submitting a form button.
A good reason for security is that it can prevent CSRF attacks, because this header can not be added to the cross domain of the AJAX request without the server's consent through CORS.
Only the following headers are allowed:
To accept
Accept-Language
Content-Language
Last-Event-ID
Content-Type
any others call the "before flight" request in the browsers supported by CORS.
Without CORS, X-Requested-With can not be added to an XHR request with a cross domain.
If the server checks the presence of this header, it knows that the request did not initiate an attempt to make a request on behalf of the user from the attacker's domain using JavaScript.
It also checks that the request was not sent from the usual HTML form, from which it is more difficult to verify that it is not a cross domain without the use of tokens. (However, checking the Origin header can be an option in supported browsers although you leave old browsers vulnerable.)
See also: https://markitzeroday.com/x-requested-with/cors/2017/06/29/csrf-mitigation-for-ajax-requests.html
So also read for greater understanding:
FormData()
https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData
Request Payload
What's the difference between "Request Payload" vs "Form Data" as seen in Chrome dev tools Network tab
As documented here, You can use the URLSearchParams API to send data in the application/x-www-form-urlencoded format using axios.
Example from offical docs:
var params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);
I am sending an AJAX request in an app running on IE.
Sometimes xhr return with an error whose status value is 10219
It seems like its not a standard HTTP status code and might be IE specific.
What could be the reasons for this error and how to fix this ?
I am using IE11.
PS: I tried googling for this but could not found anything useful. Also this is an silverlight applicatoin
I have a mobile web app that is making an AJAX request via $.get(). The request succeeds for Safari iOS, but fails for Chrome for iOS with status 0 and statusText "error".
Using tcpdump on my server, I can see that Safari sends/receives the following headers:
Accept: */* (outgoing)
Content-Type: text/plain;charset=ISO-8859-1 (returning)
Chrome for iOS adds a mime type of "image/webp" to the outgoing Accept: header and the Content-Type returned is "image/webp":
Accept: */*,image/webp (outgoing)
HTTP/1.1 200 OK
Content-Type: image/webp (returning)
Reading through the jQuery code, it looks like $.get() only parses certain content types in AJAX responses, so I'm thinking that an image mime type is just being rejected, resulting in the "error" status.
In the request from Chrome for iOS as it arrives on my server, there's also this header:
Via: 1.1 Chrome-Compression-Proxy
...which indicates that Chrome for iOS has sent the request to a Google proxy server to service the request (info https://support.google.com/chrome/answer/3517349?hl=en). Seems like this proxy server is setting the extra content type, and somehow the content type is returned as image/webp on the way back? The server code is RESTful Spring 3; I do set the content type as "text/plain" in the controller code, but somehow that's not being taken and it's still returning as "image/webp".
Has anyone had a similar problem and found a solution for it? I need to have a return Content-Type of "text/plain" to get the data back correctly to my app. This request works correctly on Chrome for Android as well AFAIK, haven't done a tcpdump for that, but the app works correctly; only fails on Chrome for iOS.
We are encountering the same issue: Chrome for iOS prefers webp, so it sends its headers as Accepts: image/webp, */*;q=0.8. The people implementing that change apparently never thought about the impact, so this causes quite a number of API's to return a 415
For more information see: https://code.google.com/p/chromium/issues/detail?id=169182
In the end we modified the server itself, since it would return a 415. On the response side, it should all go well.
I've been stacked with issue which I can't solve
for about month. You can look at the example page here: http://www.7ya.ru/travel/tours/
So, the problem is that little green form is our widget which uses cross-domain XHR and
some people have problem with it. XHR request fails. There is no request exactly. Inspector
just says "canceled". This problem occures in FF, Opera and Chrome on OSX and Win.
BUT! If you'll try to clean cache (for example in Chrome):
you will see that the widget is starts to work like a charm.
Also if you'll try to clean only a cache it wont work.
So, is anybody has ideas about which data may affect XHR requests in most browsers on two different platforms?
P.S. I've been trying to use "vanilla" XHR and jQuery version but it works same.
P.S.S. Bit of code (CoffeeScript):
lt_jq – local jQuery version ($.noConflict())
#inspect - JSON.stringify() with some additional params for formatting
request = lt_jq.ajax({
url : method,
dataType : "json",
data : params,
xhrFields : withCredentials:true
})
request.done (data)->
#request_id = (data.request_id || null)
callback?(data)
request.fail =>
console.log "Request failed [#{method}], #{#inspect(params)}"
QUESTION CLOSED, DETAILS IN COMMENTS
Does the network you're in use a caching proxy, or from the sound of it, do you have an antivirus or some sort of filter on the network which filters the requests through?
It sounds like the files are being cached without the correct headers, so the CORS headers are being cut off...
The easiest way I suggest you check this:
USING CHROME:
Clear your cache, open the dev tools, and watch the request when it
does work. Make sure you have the CORS headers in the request and response headers.
Now that you have the file in your cache, reload your page. Check that it's not working.
Now that it doesn't work, go to chrome://view-http-cache/ to view the individual cache
entries, and look for that file's request. Open it.
Check if the cached file has the CORS headers on it.
If it doesn't... make sure the proxy/antivirus doesn't cut off the CORS headers in your network, or try a different solution
I've set up Cross-Origin Resource Sharing on a server (Jetty using the CrossOriginFilter) and it works perfectly on IE8 and Firefox. On Chrome, it just ... doesn't.
$.ajax({ url : crossOriginURL,
type : "GET",
error : function(req, message) {
alert(message);
},
dataType : "json" } );
The error function is invoked, with the helpful message "error". It seems to be making the request, but without any of the headers you'd expect. If the URL is from the same origin, it works fine.
I have solved my problem this way:
Add this to your PHP Code:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true ");
header("Access-Control-Allow-Methods: OPTIONS, GET, POST");
header("Access-Control-Allow-Headers: Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control");
Or add these headers to your response.
Problem: The browsers ask to the server for options before your main request, to check if the site has the option to allow comunication with different origin, and then if yes, they do your POST or GET request.
EDIT: Try this (without your hack) to see if you're receiving data...
$.ajax({ url : crossOriginURL,
type : "GET",
error : function(req, message) {
alert(message);
},
success : function(data) {
alert(data);
},
dataType : "text"} );
what finally worked for me is xhr.setRequestHeader('Content-Type', 'text/plain');
EDIT: The server needs to add Access-Control-Allow-Headers: Content-Type to avoid this problem.
I am coming back to my own question a decade later. I don’t know if this is a good thing or a terrible thing.
It looks like the original poster may have resolved their issue, but for anyone having the same issue as commentor Elisabeth, I believe the problem may be that Chrome refuses to set a an Origin header for a CORS request if you are running the request from a local file. It won't even let you explicitly override the Origin header. This causes the server to see "Origin: null", which results in a 403 in most cases. Firefox apparently has no such constraint, as I've found after much hair-pulling.
If you absolutely need to use Chrome in this case, you can resolve your issue by running a webserver locally and always accessing your file via http: instead of via file:.
When i updated the chrome i was facing the problem,I've solved it Google Extension "Access-Control-Allow-Credentials" new version. if it is an old version,you will not need to work on a new Google Chrome version
https://chrome.google.com/webstore/detail/access-control-allow-cred/hmcjjmkppmkpobeokkhgkecjlaobjldi?hl=en
Check to make sure that you didn't set your server to both allow credentials and set the allow origin header to *. Like below:
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
If your server is returning these values for these headers, then it will not work. If you set Access-Control-Allow-Credentials to true, then you can't use *as the value of the Access-Control-Allow-Origin header. Below is an excerpt from the MDN webdocs for the header(https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin):
For requests without credentials, the literal value "*" can be specified, as a wildcard;
the value tells browsers to allow requesting code from any origin to access the resource.
Attempting to use the wildcard with credentials will result in an error.
If the above is the case, simply set Access-Control-Allow-Credentials to false.
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: false
References
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSNotSupportingCredentials
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
We actually have two domains, one is for the dashboard dashboard.app.com and another one is the public website app.com. The request was coming from the public website and the PHP routing was redirecting to the dashboard domain, that is why we got the error. The solution was to keep all the request within the same domain, without redirects.
In my case, it's localhost:8001 (the front-end) which tries to call the APIs at localhost:7001 (on server.js as a Node server). Even I had the CORS plugin installed and turned on on Chrome, still the CORS policy rejected them as preflight cases.
It took me more than half day to finally resolve the issue.
Here are the "stupid" steps, believe it or not:
i. Turn OFF the CORS plugin, reload the app, at this time you should still get the errors which are correct.
ii. Turn it back ON, reload the app, if the APIs are successful, stop here, no need to proceed to iii.
iii. However if you still get the CORS rejection, then uninstall Chrome and install an up-to-date Chrome.
iv. On the new Chrome, the previously installed CORS plugin should still be there but with OFF status.
v. Reload the page, you should get the CORS rejection messages on console which are correct.
vi. Turn it back ON, reload the page, the errors should disappear.
No further ideas if the above steps still do not work in your case.
I also tried the following on server.js (Node) and still do not work, so no bother to try:
var app = express();
var cors = require('cors'); // Already done “npm i cors --save-dev”
app.options('*', cors());
CORS will work in chrome. Just use chrome is safe-mode, i.e., use disable security settings.
Google it about it, or you can even start from command line also.