Iam trying to connect to my cloudant using just angular. The first post is successful and I am able to retrive a document/view from the cloudant with the first get method.
But when I do a successive post method I am getting a 401 unauthorised error message. Could someone please explain me what error I am doing here. Please reply in detail as I am newbie with angular and cloudant (RESTful arch)
var app = angular.module('myApp', []);
const ACCOUNTNAME = 'my acc';
const APIKEY = 'my key';
const APIPASSWORD = 'my pass';
const DATABASE = 'my db';
var cloudantDoc = 'link of document to update';
app.controller('tutorialCtrl', function($scope, $http) {
//Authentication header settings
var req = {
method: 'POST',
url: 'https://'+ACCOUNTNAME+'.cloudant.com/_session',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: 'name='+APIKEY+'&password='+APIPASSWORD,
withCredentials: true
}
$http(req).then(function(result){
//Grab data
req = {
method: 'GET',
url: 'https://'+ACCOUNTNAME+'.cloudant.com/'+DATABASE+'/_design/AllClients/_view/AllClients',
withCredentials: true
}
$http(req).then(function(result){
$scope.tableData = result.data;
console.log(result);
},
function(){
console.log("Failed at grabbing data");
});
},
function(){
console.log('Failed at authenticating');
}
);
$scope.revisionNumNews;
$http.post(cloudantDoc, JSON.stringify({"_id": "CLient1", "Client_Name":"ABC", "_rev": ""})).success(function(response){
revisionNumNews = response.rev;
});
in your code you have var cloudantDoc = 'link of document to update'
, if you are trying to update an existing document you will need to make a PUT request instead of a POST. in any case, your request should include the {withCredentials: true}
option.
if you are trying to create a new document try changing your POST request to something like this:
var databaseUrl = 'https://' + ACCOUNTNAME + '.cloudant.com/' + DATABASE
$http.post(databaseUrl, {'_id':'CLient1', 'Client_Name':'ABC'}, {withCredentials: true})
.then(function(response) {
$scope.revisionNumNews = response.rev
})
however, if you are trying to update an existing document your will need to make a PUT request and also include the document's latest _rev
. it would look something like this:
var databaseUrl = 'https://' + ACCOUNTNAME + '.cloudant.com/' + DATABASE
$http.put(databaseUrl + '/' + cloudantDocId, cloudantDoc, {withCredentials: true})
.then(function(response) {
$scope.revisionNumNews = response.rev
})
where cloudantDocId
is the document id of the document getting updated and cloudantDoc
is the updated document object (with the latest _rev
)