Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
How to use CORS with a Cloudant account.

Browser CORS Request to Cloudant

CORS is now available at Cloudant.com. This is a snippet to show how it works. It presumes a modern browser, and a Cloudant account.

You need to activate CORS for your Cloudant account first. One way to do it is with curl.

curl -i -u USERNAME -X PUT https://ACCOUNTNAME.cloudant.com/_api/v2/user/config/cors \
-H content-type:application/json \
-d '{"enable_cors":true,"allow_credentials":true,"origins":["*"]}'

The first request will give you a session cookie, called "AuthSession". It is not visible in the browser because it is marked "httpOnly". The cookie will be used for authentication in the second request. To make it work, the withCredentials = true has to come after the XMLHttpRequest is open. The cookie is valid 24 hours, so the request for the session cookie doesn't need to be done more than once for a session.

<!doctype html>
<html lang="en">
  <head>
    <title>cors</title>
    <meta charset="utf-8" />
  </head>
  <body>
    <pre class="out"></pre>
    <script>

    const ACCOUNTNAME = 'your_account_name';
    const APIKEY = 'your_api_key';
    const APIPASSWORD = 'your_api_password';
    const DATABASE = 'database_with_api_access';

    var out = document.querySelector('.out');
    // the code comes from another server than cloudant.com, so CORS is needed
    // the first request gets the AuthSession cookie (hidden in the browser)
    function firstRequest (uri, done) {
        var xhr = new XMLHttpRequest();
        xhr.open('POST', uri, true);
        xhr.withCredentials = true;
        xhr.setRequestHeader("Content-Type", 'application/x-www-form-urlencoded');
        xhr.onload = function() {
          out.textContent += 'First response: ' + xhr.responseText;
          done();
        };
        xhr.send('name='+APIKEY+'&password='+APIPASSWORD);
    }

    // the second request can now work without username and password 
    function secondRequest (uri) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', uri, true);
        xhr.withCredentials = true;
        xhr.onload = function() {
          out.textContent += '\n\nSecond response: ' + xhr.responseText;
        };
        xhr.send();
    }

    firstRequest('https://'+ACCOUNTNAME+'.cloudant.com/_session', function () {
        secondRequest('https://'+ACCOUNTNAME+'.cloudant.com/'+DATABASE+'/_all_docs');
    })

    </script>
  </body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment