Vino
Vino

Reputation: 111

XMLHTTPRequest cannot load http://... Origin http://localhost:port is not allowed by Access-Control-Allow-Origin

I was consuming some 3rd party web api and when i call that web api through ajax call in my application, always goes to error instead of success. While checking in console i got "XMLHTTPRequest cannot load http://... Origin http//localhost:port/ is not allowed by Access-Control-Allow-Origin" error

            $.ajax({
               url: "SomeURL",
               type:"GET",
               dataType: 'jsonp',
               crossDomain: true,
               success: function (data) {
                   alert("Success");
               },
               error: function (data, Errtext) {
                  alert("some error occured");
               }
           });

When i access that URL directly in browser i receive data in XML format

I also refered similar issue How to resolve uncaught syntax error in jsonp but not get the solution

Thanks in advance

Upvotes: 3

Views: 5456

Answers (1)

Saranya
Saranya

Reputation: 2008

You are able to see the response in browser because only the cross domain ajax requests are subject to same origin policy.

To overcome the limitations of same origin policy, you should use jsonp or cross-origin resource sharing(CORS).

JSONP: What is JSONP all about?

Please note that to use jsonp , the third party web api you are calling should support jsonp.

CORS : The Cross-Origin Resource Sharing standard works by adding new HTTP headers that allow servers to describe the set of origins that are permitted to read that information using a web browser. Additionally, for HTTP request methods that can cause side-effects on user data (in particular, for HTTP methods other than GET, or for POST usage with certain MIME types), the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with an HTTPOPTIONS request method, and then, upon "approval" from the server, sending the actual request with the actual HTTP request method. Servers can also notify clients whether "credentials" (including Cookies and HTTP Authentication data) should be sent with requests.

https://developer.mozilla.org/en/docs/HTTP/Access_control_CORS

To enable CORS in an asp.net application:

<system.webServer>
 <httpProtocol>
  <customHeaders>
   <add name="Access-Control-Allow-Origin" value="*" />
   <add name="Access-Control-Allow-Headers" value="Content-Type" />
  </customHeaders>
 </httpProtocol>
</system.webServer>

Upvotes: 1

Related Questions