javascriptjqueryeasypost

Calling Easypost API from browser client javascript


I am trying to call Easypost APIs from javascript/jquery (yes, I know it is a "bad" idea because the JS code contains the cleartext account key, but this JS and HTML are in a secure section of our web site available only to specifically authorized people).

My call is like:

$.ajax({
    url: uri,
    type: "POST",
    data: JSON.stringify(data),
    contentType: "application/json",
    headers: {
        "Authorization": "Basic " + btoa(username + ":" + password)
    },
    success: function(result) {...},
    error: function(...) {...}
 });

It returns 404 and Chrome shows this error:

Failed to load https://api.easypost.com/v2/shipments: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost' is therefore not allowed access. The response had HTTP status code 404.

Is this possible?


Solution

  • That means the easypost API server does not accept CORS request or requests originating from localhost.

    Based on their documentation, they only provide server side libraries to interact with their API. My guess is you won't be able to interact directly with it from your web app.

    Your best bet is to use a proxy, you can develop one yourself or use something like node-http-proxy to proxy your API calls. (There are php or python equivalents)

    The proxy server will be able to issue the requests and will then forward them to your app.

    Suggested further reading: type understanding CORS on google and read more about it.