Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GET working with Postman, but not with Ajax?

I'm attempting to do a simple GET request from a server hosting some account data. The request requires an Authorization header in order to function correctly. I have performed the GET request and retrieved the data successfully in Postman, but attempting to do so in Javascript via Ajax results in a "Invalid HTTP status code 405" error.

Below is a link to a fiddle and a screenshot of the Postman settings. Thanks.!

$.ajax({
    beforeSend: function(xhrObj){
            xhrObj.setRequestHeader("Authorization","Bearer tj7LTLycpQC6DRup5BkHUO7uVbYaAZI40");
    },
    type: "GET",
    url: "https://api05.iq.questrade.com/v1/accounts",
    success: function(e){
            console.log(e)
    }
});

http://jsfiddle.net/Ldjbp2j8/1/

POSTMAN SETTINGS

like image 480
thebighoncho Avatar asked Jul 16 '15 23:07

thebighoncho


2 Answers

From Chrome's JS console:

Failed to load resource: the server responded with a status of 405 (Method Not Allowed)

Because you are adding an Authorization header, you have made the request complex. This requires the browser to make a preflight OPTIONS request to ask for permission to send the complex request.

The server you are making the request to is responding saying that OPTIONS requests are not allowed to that URL.

You will need to modify the server so that it responds appropriately to the preflight CORS request.


Postman doesn't need to make a preflight request because your browser trusts Postman's code. It doesn't know if it can trust the code it received from JSFiddle (AKA potential evil hacker site) with the data api05.iq.questrade.com (AKA potential online banking or company Intranet site) is willing to share with it.

like image 70
Quentin Avatar answered Oct 03 '22 06:10

Quentin


Look at the console errors:

XMLHttpRequest cannot load https://api05.iq.questrade.com/v1/accounts.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://fiddle.jshell.net' is therefore not allowed access. The response had HTTP status code 405.

This is the CORS issue. Browsers sent OPTIONS aka pre-flight request to the server if the domain doesn't match with the domain of the running code. And you must add the required headers to the responses as well.

You must modify server to handle that.

You can also use JSONP as an alternative.

like image 29
Xeon Avatar answered Oct 03 '22 05:10

Xeon