0

When i call rest api from java script , i will get an error "Access to XMLHttpRequest at 'https://localhost:44300/api/sample?Empno=1234' from origin 'http://localhost' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status."

Below the java script i used

 const formData = new FormData();
 const response = new XMLHttpRequest();
 response.open("GET", "https://localhost:44300/api/sample?Empno=1234");

response.setRequestHeader('key', '@1234');
response.send(formData);

response.onload = (e) => {
    alert(response.response);
}

And below the jquery

  alert('ajax');
     $.ajax({ 
         type: "GET",
         dataType: "json",
         beforeSend: function (request) {
             request.setRequestHeader('key', '@1234');
         },
         url: "https://localhost:44300/api/sample?Empno=1234",
         success: function(data){        
            alert(data);
         }
     });

In rest api web config i added this tag for enable cros policy

   <httpProtocol>
 <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" /> 
   </customHeaders>
 </httpProtocol>

But when i call rest api from server side code and if using Postman Agent,it works fine, only problem when i call from java script or jQuery,Pls help to resolve this problem.

Note:Rest api and call rest api on same machine

Regards and Thanks Aravind

Aravind Aravind
  • 179
  • 1
  • 10
  • You need to add CORS headers to the response as you're making a cross domain request (even different port numbers on the same host counts as cross-domain). Given you've shown the attempt you made to set the headers in the XML config, it would appear this has not worked. – Rory McCrossan Mar 04 '21 at 10:54
  • Assuming you're using .Net Core WebAPI 3, then [this](https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-5.0#cors-with-named-policy-and-middleware) is how you do it. Otherwise, simply Googling 'CORS' alongside the REST API technology you're using should find the relevant solution. – Rory McCrossan Mar 04 '21 at 10:57

0 Answers0