0
votes

I'm using cloudant, CORS is enabled, all queries are working except _find.

My find query is working very well against a local CouchDB with this code:

var urlPrefix = "http://localhost:5984/etablissements";

var query = {
  "selector": {
   "cp": 24000
  }
};

$.ajax({
    type: "POST",
    url:  urlPrefix + '/_find',
    contentType: "application/json", 
    data:JSON.stringify(query),
    success: function(data) {
           console.log(data.docs);
            // do whatever with data.docs there

     }

 });

Now, I want to make a CORS jQuery AJAX call online, and do the same query as my first one, against my IBM Cloudant database, but it doesn't work, while it is the same query, and the same replicated database.

CORS is enabled on Cloudant.

urlPrefix = "https://USERNAME:[email protected]/etablissements";

    var query = {
      "selector": {
       "cp": 24000
      }
    };
    $.ajax({
        type: "POST",
        url:  urlPrefix + '/_find',
        contentType: "application/json", 
        data:JSON.stringify(query),
        dataType: 'json',

        crossDomain: true,
        xhrFields: {
             'withCredentials': true // tell the client to send the cookies if any for the requested domain
          },
        success: function(data) {
            console.log(data.docs);

            }
        },
        error:function(data){
            console.log(data);
        }

     });

I haven't received any error message coming from Cloudant. I just get this error message from jQuery:

  {…}
​
abort: function abort()
​
always: function always()
​
catch: function catch()
​
done: function add()
​
fail: function add()
​
getAllResponseHeaders: function getAllResponseHeaders()
​
getResponseHeader: function getResponseHeader()
​
overrideMimeType: function overrideMimeType()
​
pipe: function pipe()
​
progress: function add()
​
promise: function promise()
​
readyState: 0
​
responseJSON: undefined
​
setRequestHeader: function setRequestHeader()
​
state: function state()
​
status: 0
​
statusCode: function statusCode()
​
statusText: "error"
​
then: function then()
​
__proto__: Object { … }

Others query from this document (like 'all' for example) are currently working:

http://bradley-holt.com/2011/07/couchdb-jquery-plugin-reference/

EDIT : Glynn, Still gettin the same error with the lastest firefox version and your copy pasted code, no ajax call is done, instead, it goes through the jquery error process :

enter image description here

EDIT 2 : I've changed a few Glynn's code and it has worked in chrome but i've had to provide credentials inside a popup coming from Chrome. Please notice that i've removed the login password from the urlPrefix variable, and that the username and password provided inside jquery are not working. So it is not the good solution yet. Firefox is still failing with the error showed above :

 <html>
    <body>
      <script
        src="https://code.jquery.com/jquery-3.3.1.min.js"
        integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
        crossorigin="anonymous"></script>
      <script>
     var urlPrefix = "https://1c54473b-be6e-42d6-b914-d0ecae937981-bluemix.cloudant.com/etablissements";
      var query = {
        "selector": {
         "cp": 24000
        }
      };
      $.ajax({
          type: "POST",
          url:  urlPrefix + '/_find',
          contentType: "application/json", 
          data:JSON.stringify(query),
          dataType: 'json',
          crossDomain: true,
          username: "xxxxxxx-xxxxxxx-42d6-xxxxxx-xxxxxx-bluemix",
          password:"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
          xhrFields: {
               'withCredentials': true // tell the client to send the cookies if any for the requested domain
            },
          success: function(data) {
              console.log(data);
          },
          error:function(data){
              console.log(data);
          }
       });
       </script>
    </body>
    </html>

enter image description here

EDIT 3 : SOLVED !

I have succeeded to make it work with the help of this page : https://zinoui.com/blog/ajax-basic-authentication

So this is my final code, tested in firefox, chrome and opera, and finally working ! So i'm now able to do _find queries with CORS enabled on cloudant and i LOVE IT !

Please notice that the key to the solution was the jquery beforeSend() function, you need to provide the credentials there :

   <html><meta charset="utf-8" />
    <head>
    <title>JS Bin</title>
    </head>

    <body>
      <script
        src="https://code.jquery.com/jquery-3.3.1.min.js"
        integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
        crossorigin="anonymous" charset="utf-8"></script>
      <script>
     var urlPrefix = "https://1c54473b-be6e-42d6-b914-d0ecae937981-bluemix.cloudant.com/etablissements";
     var USERNAME = "xxxxxxxx-xxxxxxxx-42d6-b914-d0ecae937981-bluemix";
     var PASSWORD = "xxxxxxxxxxxxxxxxxb9e74af7368b21a37b531aae819929d3405c7d22";

      var query = {
        "selector": {
         "cp": 24000
        }
      };
      $.ajax({
          type: "POST",
          contentType: "application/json", 
          data:JSON.stringify(query),
          dataType: 'json',
          crossDomain: true,
           xhrFields: {
               'withCredentials': true // tell the client to send the cookies if any for the requested domain
            },
            beforeSend: function (xhr) {
             xhr.setRequestHeader('Authorization', 'Basic '  + btoa(USERNAME + ":" + PASSWORD));
          },
            url:  urlPrefix + '/_find',

          success: function(data) {
              console.log(data);
          },
          error:function(data){
              console.log(data);
          }
       });


       </script>
    </body>
    </html>

Doing CORS apps is so usefulll for building quick labos apps ! I love this no server technology, please DONT STOP this !!

1
I don't know if you're aware but PouchDB would highly simplify access to cloudant. Also, what is the http response from your request? You can see that in the dev consoleAlexis Côté
Hello Alexis, yes, i love the pouchdb technology, but i'm willing to make couchdb works 100% before using pouchdb . thank you ! in this case, there was no http response at all, only the jquery error displayedjojo45
i dont want to use pouchdb for now, i dont want to get a local replication.jojo45
You can use PouchDB as a client for your remote database. There's no need for local databaseAlexis Côté
Really ? Wow thats a nice information ure giving me !jojo45

1 Answers

0
votes

When debugging such thins, I would first check whether your query works from the Cloudant Dashboard or from the command-line:

curl -X POST \ 
  -d'{"selector": { "cp": 24000}}' \ 
  -H'Content-type: application/json' \
 "https://USERNAME:[email protected]/etablissements/_find"

The answer is "yes, it works!". You get an object back that contains {"docs": [ ... ]} with an array of documents.

So I set about testing your jQuery code, and it works if you remove the rogue } in the success function:

<html>
<body>
  <script
    src="https://code.jquery.com/jquery-3.3.1.min.js"
    integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
    crossorigin="anonymous"></script>
  <script>
  var urlPrefix = "https://USERNAME:[email protected]/etablissements";
  var query = {
    "selector": {
     "cp": 24000
    }
  };
  $.ajax({
      type: "POST",
      url:  urlPrefix + '/_find',
      contentType: "application/json", 
      data:JSON.stringify(query),
      dataType: 'json',
      crossDomain: true,
      xhrFields: {
           'withCredentials': true // tell the client to send the cookies if any for the requested domain
        },
      success: function(data) {
          console.log(data.docs);
      },
      error:function(data){
          console.log(data);
      }
   });
   </script>
</body>
</html>

N.B Please don't publish your Cloudant credentials in the public domain.