Lara
Lara

Reputation: 3021

"NetworkError: 405 Method Not Allowed error in Ajax Call

I have created a RESTservice and i tested it on Chrome REST Console . There its working fine and i am getting the response but while consuming the same by jquery Ajax i am getting "NetworkError: 405 Method Not Allowed error in Ajax Call and Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:64132/Auth. (Reason: CORS request failed). error.Here is my Ajax code..

var UserDetails = { "UserName": "Bond", "Password": "password" };

$.ajax({
    type: 'POST',
    url: 'http://localhost:64132/Auth',
    crossDomain: true,
    data: UserDetails,
    contentType: "application/json; charset=utf-8",
    success: function (data) {

        alert(data.UserName);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert("some error");
    }
});

Please help me to correct this and successfully call the Service.Thanks..

Update

when i am trying to call the Service from Chrome i am getting following error in console..

Failed to load resource: the server responded with a status of 405 (Method Not Allowed)
Test.html:1 XMLHttpRequest cannot load http://localhost:64132/Auth. No  'Access-Control-Allow-Origin' header is present on the requested resource.  Origin 'null' is therefore not allowed access. The response had HTTP status code 405.

Upvotes: 1

Views: 14154

Answers (1)

CupawnTae
CupawnTae

Reputation: 14580

Modern browsers have very strict rules about retrieving content from different "domains". Retrieving content from your local file system (your HTML/script) is not the same as making a network request to localhost (your ajax call), so Chrome treats it as a cross-domain request.

In order for the cross-domain request to succeed, you either need to serve the HTML content/script from a http://localhost:64132/ URL as well (so they're in the same domain), or you need to set up your REST service to implement the CORS dance to allow your file: URL to access it.

Without knowing the details of how your REST service is implemented, it's impossible to give specific instructions for either option. Which you choose will will depend on how you intend to deploy the page and service in real life (same domain or not) and ease of implementation. If your REST service is deployed in some sort of container it may provide options for implementing CORS, and/or for serving the initial page.

Random example of the same issue (although the exact solution here is unlikely to work for your specific case): Access-Control-Allow-Origin header when Origin 'null' when trying to post data to a LOCAL application

Upvotes: 1

Related Questions