Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Axios vs jQuery post CORS issue #113

Closed
benjamingeorge opened this issue Sep 25, 2015 · 48 comments
Closed

Axios vs jQuery post CORS issue #113

benjamingeorge opened this issue Sep 25, 2015 · 48 comments

Comments

@benjamingeorge
Copy link

When doing a CORS post request, jQuery succeeds but Axios gets a CORS error in the console.

This gets a CORS error

Axios.post(endpoint, { email_address : emailAddress})
      .then(function (response) {
        isSentSuccessful = true;
      })
      .catch(function (response) { 
        errorAnimation();
      });

But this works

    jQuery.post(endpoint, { email_address : emailAddress },
        function(resp){
         isSentSuccessful = true;
        })
        .fail(function(resp){
          errorAnimation();
        });

Am I missing something with Axios? My server is already configured for CORS requests.

@mzabriskie
Copy link
Member

What is the error that you are getting?

@benjamingeorge
Copy link
Author

OPTIONS 
XMLHttpRequest cannot load http://example/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://example.dev' is therefore not allowed access. The response had HTTP status code 404.

is jQuery sending something that Axios isn't? Headers or preflight ?

@mzabriskie
Copy link
Member

What browser are you using when you get this error?

@benjamingeorge
Copy link
Author

Chrome 45

@mzabriskie
Copy link
Member

Will you try making this request from your app, and let me know the result?

axios.get('https://api.github.com/users/benjamingeorge')
  .then(function (res) {
    console.log(res.data);
  })
  .catch(function(res) {
    if(res instanceof Error) {
      console.log(res.message);
    } else {
      console.log(res.data);
    }
  });

@benjamingeorge
Copy link
Author

Sorry for the delay. I get an object back with all the data. Again, it's not get methods that are the problem, it's the POST method that has the issue.

@peterpuzos
Copy link

+1

1 similar comment
@arpitHub
Copy link

+1

@anttti
Copy link

anttti commented Dec 5, 2015

Stumbled upon this very same issue. jQuery AJAX POST works, Axios (and isomorphic-fetch FWIW) POSTs fail in the preflight phase. What's even more weird is if I "Copy as cURL" both of the requests from Chrome inspector's network tab, they're identical!

@hlindquist
Copy link

I had this problem as well, but I got it working now as I simply had Access-Control-Allow-Origin set up wrong on the server side. I suspect that the rest of you have this as well because jquery POST sends the requests as application/x-www-form-urlencoded as default, and thus doesn`t get preflighted. While axios correctly sends it as application/json and will be preflighted.

@rafaeleyng
Copy link

👍

@rafaeleyng
Copy link

I was setting up a little API to learn Grails. Doing a POST request, only by changing from jQuery to Axios, I went from getting this:

screen shot 2015-12-23 at 3 36 45 pm

to this:

screen shot 2015-12-23 at 3 35 43 pm

@ajacquelin
Copy link

+1

@peterpuzos
Copy link

Homyk -> What CORS setting did you change on the server side to properly accept application/json in preflight with AXIOS? Can you explain? For example, I am using Tomcat, and sending post requests "with credentials" and Axios is not working for us.

@hlindquist
Copy link

peterpuzos -> I`m using embedded Jetty, but an equivalent will exist for tomcat.

FilterHolder filter = new FilterHolder();
filter.setInitParameter("allowedOrigins", "*");
filter.setInitParameter("allowedMethods", "POST,GET,OPTIONS,PUT,DELETE,HEAD");
filter.setInitParameter("allowCredentials", "true");
CrossOriginFilter corsFilter = new CrossOriginFilter();
filter.setFilter(corsFilter);

allowedOrigins setting should have a specific IP in prod.

@peterpuzos
Copy link

Thanks for the advice. We actually managed to get it working after doing some reconfiguration (removed CXF from the equation). We can confirm that it doesn't seem to be an AXIOS issue at all! Cheers!

@mdarif
Copy link

mdarif commented Mar 28, 2016

+1

5 similar comments
@dmavrin
Copy link

dmavrin commented Mar 29, 2016

+1

@mcfa77y
Copy link

mcfa77y commented Mar 30, 2016

+1

@AndrejGajdos
Copy link

+1

@f14c0
Copy link

f14c0 commented Apr 6, 2016

+1

@steelx
Copy link

steelx commented Apr 27, 2016

+1

@leyume
Copy link

leyume commented Apr 28, 2016

Another way to deal with this, especially if it worked in jQuery

var config = {
       headers: {
             'Content-Type': 'application/x-www-form-urlencoded'
       },
       params: {
             email_address: emailAddress
       }
};
axios.post( endpoint, {}, config)
.then(function (response) {
       console.log(response);
})
.catch(function (response) {
       console.log(response);
});

From Homyk comment on Dec 9, 2015, was able to come up with this and it worked.

@steelx
Copy link

steelx commented Apr 29, 2016

@leyume
still doesnt work, you can check it here, OPTIONS call goes thru, but POST call fails
https://reduxapp.herokuapp.com/signin

@pdewouters
Copy link

pdewouters commented May 14, 2016

@steelx were you able to find a solution? I have the same issue, OPTIONS is successful. but POST throws an error.

EDIT: nevermind, was an issue with DB connection

@dhirajbasukala
Copy link

Spent almost a day testing POST request via Axios with unsuccessful result. The Jquery worked just out of the box. After trying out all suggested setting none worked and frustrating. Later I compared the data being sent by Axios POST and jquery POST and the source format in Chrome Dev Tool showed; jquery sent data in the url string fromat i.e., x=1&y=10&z=abc... while I was sending data via Axios as
json object {x:1, y:10,z:"abc"} as shown in examples. Later I changed it to url string format and it just worked. Hope it helps some one. However I don't know why it worked at first place, since all the examples in git repo shows sending json object in post requst.

@unuigbee
Copy link

unuigbee commented Jul 3, 2016

Hi @dhirajbasukala I'm having the same issue. Can you post an example please?

@crazy4groovy
Copy link

+1 issue

@dhirajbasukala
Copy link

@unuigbee, below is example that worked for me.
axios.post(url,'key1=value1&key2=value2',{withCredentials: true}) .then((res)=>{console.log(res)) .catch((res)=>{console.log(res))

where as earlier JSON object being sent case didnt' work which was as below:
axios.post(url,{"key1":"value1","key2":"value2"},{withCredentials: true}) .then((res)=>{console.log(res)) .catch((res)=>{console.log(res))

I hope it helps.

@unuigbee
Copy link

unuigbee commented Jul 5, 2016

@dhirajbasukala Thanks I tried it but it didn't work. I had to set Headers for Access-Control-Allow-Origin to all (*) on my dev server. I know it's not safe but I had to for testing purposes.

@hadv
Copy link

hadv commented Jul 12, 2016

+1

@image72
Copy link

image72 commented Jul 18, 2016

maybe you need check server accepts content type, I used angular $http from jquery.ajax encounter this problem.
just set like that

$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';

jquery v1 default content-type is 'application/x-www-form-urlencoded;charset=utf-8'

@rubennorte
Copy link
Member

I'm closing this issue as it's the expected behaviour. We're considering adding a new parameter to automatically configure the content-type and the data parsing, but that's a different issue.

@afilp
Copy link

afilp commented Oct 11, 2016

@rubennorte Is this automatic configuration implemented?

@afilp
Copy link

afilp commented Oct 15, 2016

@mzabriskie Is the above automatic configuration idea about to be implemented? It appears that this makes it difficult to use axios, for certain use cases. Thanks in advance!

@asphalt2018
Copy link

I tried param like "a=3&b=4", it works

@Pau1fitz
Copy link

+1

@bboydflo
Copy link

as @leyume said, if it worked with jquery, than passing config object with headers
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },

fixed the problem for me. Also make sure to have "Access-Control-Allow-Origin" = "*" set on the server side.

@jartaud
Copy link

jartaud commented Mar 25, 2017

I've spent all night trying to make axios work. It always sends OPTIONS instead of POST and my CORS cofiguration gets ignored. Vue Resource works for me.

Vue.js 2 (front), Laravel 5.4 (api), Ubuntu (dev machine), Google Chrome & Firefox

@allexon
Copy link

allexon commented Apr 13, 2017

HTTPS cors HTTP? Hello, how do I communicate using React axios. Accurate
Localhost request: https: appmix: 3001
Server: http://cepaberto.com.br/api/v2/cep.json?cep=xxxxxxxxx

@Jerjomins
Copy link

+1

1 similar comment
@apurav2007
Copy link

+1

@jacekgalazka
Copy link

jacekgalazka commented Jan 24, 2018

you can must use qs to serialize your data
const qs = require('qs'); const data = qs.stringify({ data1: 'a', data2: 'a', data3: 'a', }); axios.get('host', data, { 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', 'Access-Control-Allow-Origin':'*' })

@reducio
Copy link

reducio commented Feb 2, 2018

+1

2 similar comments
@mkyukov
Copy link

mkyukov commented Jun 5, 2018

+1

@maynardewm
Copy link

+1

@Ethan0007
Copy link

Hello,

I just want to ask if how can i do it in get request when in CORS?
it seems its not working when i tried this:
image

But when i used jquery get request, it allows me to access the api.

Thanks.

@travisC
Copy link

travisC commented May 19, 2020

@Ethan0007 Swap your header to:

headers: { "Content-Type": "application/x-www-form-urlencoded" },

Otherwise the server/api will need to accept application/json. See the example above for the backend fix in jetty:
#113 (comment)

@axios axios locked and limited conversation to collaborators May 21, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests