0

we recieved follwing error while using REST API.

"No 'Access-Control-Allow-Origin' header is present on the requested resource."

Below my code

  function get_XmlHttp() 
{
    var xmlHttp = null;
   if(window.XMLHttpRequest) {   // for Forefox, IE7+, Opera, Safari, ...
        xmlHttp = new XMLHttpRequest();
    }
    else if(window.ActiveXObject) { // for Internet Explorer 5 or 6
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    return xmlHttp;
}

    form_data = new FormData();
    form_data.append('login',login);
    form_data.append('key',key);
    form_data.append('token',token);


var request = get_XmlHttp();
    request.open("POST", "myapi", true); 
    request.setRequestHeader('Access-Control-Allow-Headers', '*');
request.setRequestHeader('Access-Control-Allow-Origin', '*'); 
    request.send(form_data);

  request.onreadystatechange = function() {
        if (request.readyState == 4) {
          alert(request.responseText);
        }
    }

we are also googled and found solutions but not working.

please help me and thanks in advance.

  • 1
    Hi, welcome to stackoverflow! The `Access-Control-Allow-Origin` must be set from server and not the client. Before sending a POST request, an OPTIONS request is sent to server from browser, In the response of this, the server sends the required headers, methods and other stuff. This must be set from server side and not client. – itaintme Sep 03 '18 at 23:05
  • hello sir, we also set in to php header, but not working. please give me example. with thanks – Arsalan khatri Sep 04 '18 at 07:16
  • have you set headers for just POST request or OPTIONS request as well? Add your php code here as well – itaintme Sep 04 '18 at 12:46

1 Answers1

-1

While you did not mentioned which server are you using, here's two links about how to configure the Access-Control-Allow-Origin header on popular HTTP Servers.

Please note: you wouldn't like to use *, but you might want to properly configure your server to enable this for known hosts only.

fabrik
  • 14,094
  • 8
  • 55
  • 71