javascript - XMLHttpRequest gives CORS error where as $.ajax works -


the jquery ajax code works absolutely fine

  $.ajax({   url: rumi_api_endpoint + rumi_params + "filter/show",   data: {"name":"ronak","country":"india"}, //return  data   datatype: 'json',   type: 'post',   async: true,   success: function (res) {     oncomplete(res);   },   error: function () {     console.log('save error.');   } }); 

but native javascript xmlhttprequest throws cors error.

if (window.xmlhttprequest) {   xmlhttp=new xmlhttprequest(); } else {   xmlhttp=new activexobject("microsoft.xmlhttp"); } xmlhttp.onreadystatechange = function () {   if (xmlhttp.readystate==4 && xmlhttp.status==200) {     oncomplete(res);   } } xmlhttp.open("post",rumi_api_endpoint + rumi_params + "filter/show",true); xmlhttp.setrequestheader("content-type","application/json; charset=utf-8"); var xyz = {   "config": {"name":"ronak","country":"india"},   "token": "abc" } xmlhttp.send(json.stringify(xyz)); 

when set content-type x-www-form-urlencoded, able send request stringified json. when don't set header, returns 406 not acceptable error. when want send json, gives cors error. there missing using native javascript approach?

the jquery ajax request sending considered "simple" , therefore follows sop less strictly (it doesn't send options request.) native javascript ajax request sending not considered "simple" because added content-type header.

to fix this, you'll of course need remove content-type header, , since no longer setting content-type header application/json, you'll have format data valid paramstring. jquery it's simple $.param(xyz), however, i'm assuming you're trying without jquery, you'll need data formatted

config%5bname%5d=ronak&config%5bcountry%5d=india&token=abc 

Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -