Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling External API with Javascript

I need to make a POST request to an external server from my webpage using Javascript. The body and response are both json. I can't figure out how to make this call or what tools to use. How do I make this call?

This is what I have so far using jQuery and ajax:

var body = '{"method":"getViews","params":{"filter":{"operator":"and","clauses":[{"operator‌​":"matches","value":"'+ inputValue +'"}]},"order":[{"field":"name","ascending":true}],"page":{"startIndex":0,"maxIt‌​ems":5}}}';
var response = $.ajax({
           url: "http://" + environment + "/vizportal/api/web/v1/getViews",
           method: "post",
           dataType:'json',
           data: JSON.stringify(body),
           headers: {
            'Content-Type': 'text/plain',
            'X-XSRF-TOKEN' : XSRFToken,
            'Cookie': 'workgroup_session_id='+workgroupSessionId+';XSRF-TOKEN='+XSRFToken
           },
           success:function(response){
                alert("success");
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) { 
                alert("Status: " + textStatus); alert("Error: " + errorThrown); 
            } 
        });

It is throwing a alerts that just says "Status:" and "Error:"

The console says this "XMLHttpRequest cannot load http://[domain]/vizportal/api/web/v1/getViews. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://[domain]' is therefore not allowed access. The response had HTTP status code 405."

like image 868
anton2g Avatar asked Oct 23 '15 19:10

anton2g


People also ask

Can JavaScript make API calls?

There are many different ways to make an API call in JavaScript ranging from using vanilla JavaScript to jQuery to using other tools that vastly simplify making API calls.

How do you access an API with JavaScript?

Approach: First make the necessary JavaScript file, HTML file and CSS file. Then store the API URL in a variable (here api_url). Define a async function (here getapi()) and pass api_url in that function. Define a constant response and store the fetched data by await fetch() method.

Can I call API from browser?

You can use any HTTP client to invoke your web API. In fact, you can invoke it directly from a web browser.


1 Answers

Are you the owner of the destination of the call? If yes, implement the CORS headers in server-side.

If no, you can fiddle using JSONP (it bypasses CORS) or you can even implement a server-side proxy that you own to route external requests (and of course, implement CORS there).

Check out the article on CORS in MDN if you want more information : HTTP access control (CORS) on MDN

like image 112
Mathieu Amiot Avatar answered Sep 28 '22 18:09

Mathieu Amiot