eNtsa2019 Mkontwana
eNtsa2019 Mkontwana

Reputation: 103

How to fix the cors origin error on Jquery when POST method fails?

Hi Team i have the following error and can't seem to fix it, my post method keeps on fails either when i do Rest client request on Visual Studio code either not browser or any Restful tool.

jquery.js:9664 POST ->url<- 404 (Not Found)

Access to XMLHttpRequest at X from origin Y has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

//Javascript code for this error.

 // button for switch functionality on/off.
  $(document).ready(function() {
    $('#toggle_event_editing ').click(function(){
      if($(this).hasClass('locked_active')) {
      $('#switch_status').html('Switched off');
        $.ajax({
          url:'myurl',
          type:'POST',
          data:{
            payload_raw: 'AAA',
            dev_id:'mkr1300'
          },
         success:function(response){
         alert(response);
          },
         error:function() {
           $('#error').text("There was an error while processing your request. Please try again");
          }
        }); 

    }else{
    $('#switch_status').html('Switched on.');
    $.ajax({
      url:'myurl',
      type:'POST',
      data:{
        payload_raw:'AAE',
        dev_id:'mkr1300'
      },
      success:function(response) {
      alert(response);
      },
      error:function() {
      $('#error').text("There was an error while processing your request.Please try again");
      }
    });
    }
    });
  });

Upvotes: 3

Views: 233

Answers (1)

Ali Maleki
Ali Maleki

Reputation: 300

I think that your backend is blocking request. the shortest solution is adding this block of code to your webconfig in backend project :

<httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="application/json" />
        <add name="Access-Control-Allow-Method" value="GET,POST,PUT,DELETE,OPTIONS" />
      </customHeaders>
</httpProtocol>

Upvotes: 1

Related Questions