简体   繁体   中英

Ajax request to restful api from different domain

I have a restful api that works normally when i am calling from the postman. On postman i am giving the following configuration to get answer: -POST: " https://www.example.net/API/MyFunction " I have no authorization. -Headers: Content-Type : application/json, username:myusername, password:mypassword -Body raw

{"firstparameter":"firtparameter_value"}

I have a pure html domain where i would like to make some calls and provide data from this api. So i added a link to the jquery-3.3.1.js and create an ajax call. I tried to follow this guide https://www.html5rocks.com/en/tutorials/cors/ but when i run the call i am getting the bellow error. Ajax call:

 var username = 'myusername';
 var password = 'mypassword';
$.ajax({

    type: 'POST',
    dataType: "jsonp",

    url: 'https://www.example.net/API/MyFunction',


    contentType: 'text/plain',
    crossDomain: true,
    data:{"firstparameter":"firtparameter_value"},
    xhrFields: {

        withCredentials: false
    },

    headers: {


        username: username,
        password: password
    },

    success: function () {


    error: function () {

    }
});

the error i am geting is :

GET https://www.example.net/API/MyFunction/?callback=jQuery33104247946565223606_1541427224545&firstparameter=firtparameter_value&_=1541427224546 net::ERR_ABORTED 405 (Method Not Allowed)

 type: 'POST', dataType: "jsonp", 

JSONP requests work by injecting a <script src> element which makes a GET request. The method property is ignored by jQuery when you use JSONP.

You cannot make a POST request with JSONP.

A REST API is unlikely to return JSONP (which was a hack to work around the Same Origin Policy in the bad old days before we had CORS — and, like CORS, it must be set up on the server ). Your API certainly does not because it is telling you the GET method (required for JSONP) is not allowed.

Set the correct value for dataType .


You have some other problems, but they are not related to the error message.

You said " -Headers: Content-Type : application/json " but then in the JS " contentType: 'text/plain' " — use the correct content-type.

You said " data:{"firstparameter":"firtparameter_value"} " but jQuery will encode that in URL format not JSON format. You need to explicitly encode it as JSON with JSON.stringify .

That error happens whenever you try to call an API function with the wrong Method, for example call a POST function with a Get Ajax call.

You need to be sure that your backend has the method your calling from ajax as POST

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM