Adding document in Couchbase and missing JSON body

2019-08-04 19:29发布

问题:

I am trying to use Couchbase REST API to add a document to the existing documents. I am just testing this in Postman while writing on the code.

POST:

http://<ip>:8091/pools/default/buckets/<bucketname>/docs/testdoc1?rev=1

Headers:

Accept: application/json
Authorization : xxxxx

Body:

Raw JSON (application/json)
{
  "Name": "xxx",
  "Address": "yyy",
  "Phone number": "xxxx",
  "Badge": "yyy",
  "BadgeType": "xxx"
} 

When I send above in Postman, It is adding this new doc. under couchbase documents/bucket, but on the body field it shows like, "Binary Document, base64 not available"

I tried even from my html code, but json body didn't receive at couchbase end.

<!DOCTYPE html>
<html>
<body>

<input type="submit" value="Start" onclick="submit()">

<script type="text/javascript">
var params = {
  "Name": "xxx",
  "Address": "yyy",
  "Phone number": "xxxx",
  "Badge": "yyy",
  "BadgeType": "xxx"
} 
    function submit() {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                alert(xhr.response);
            }
        }
        xhr.open('post', 'http://<ip>:8091/pools/default/buckets/<buckname>/docs/testdochtml?rev=1', true);
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.setRequestHeader('Accept', 'application/json');
        xhr.setRequestHeader('Authorization', 'Basic ' + 'xxxxxxx');

        xhr.send(JSON.stringify(params));
    }
</script>

<p>Click on the submit button.</p>

</body>
</html>

Can someone guide me why is that JSON not going to couchbase in a correct way?

回答1:

First off: as far as I know, this endpoint is not supported and it is not documented. If you see somewhere that it is supported, let me know, because I think that needs corrected. You should use one of the SDKs (Java, .NET, Node, etc) instead.

That being said, I was able to get it working via Postman. You can't just send raw JSON as the document. You need to POST encoded form data. One of the values this endpoint expects is "value", which contains the encoded JSON document.

Here's an example of what I did (I called my bucket "so"):

POST /pools/default/buckets/so/docs/testdoc2 HTTP/1.1
Host: localhost
cache-control: no-cache
Postman-Token: ba87ef4e-4bba-42b4-84da-ae775b26dbcb
value=%7B%0A%09%22Name%22%3A+%22xxx%22%2C%0A%09%22Address%22%3A+%22yyy%22%2C%0A%09%22Phone+number%22%3A+%22xxxx%22%2C%0A%09%22Badge%22%3A+%22yyy%22%2C%0A%09%22BadgeType%22%3A+%22xxx%22%0A%7D%0A

Note that value above is just the URL-encoded JSON from your question (Postman encoded it for me, and Postman must have added the cache-control header on its own too, because I did not specify that):