AngularJS CouchDB, get data with authentication - angularjs

Simple AngularJS script with user:passw and server.ip
<!DOCTYPE html>
<html >
<script src= "angularjs/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<p>{{ names }}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', ['$scope','$http', function($scope,$http) {
$http.get('http://user:passwd#server.ip:5984/dbp/3c9f8c470a4a40d81d43467346000010')
.success(function (data) {
$scope.names = data.rows;
});
}]);
</script>
</body>
</html>
If I use url & put in address bar in my browser, everything works fine
http://user:passwd#server.ip:5984/dbp/3c9f8c470a4a40d81d43467346000010
I mean I get json data.
When I use previous script I get
Remote Address:server.ip:5984
Request URL:http://server.ip:5984/dbp/3c9f8c470a4a40d81d43467346000010
Request Method:GET
Status Code:401 Unauthorized
How can I get json data from CouchDB with authorization header in AngularJS?
CouchDB & AngularJS are on the same server!
I read all 111 q/a (AngularJS CouchDB) from stackoverflow and I didn't find right answer.
I have enable CORS!

You have to send the username/password pair in an Authorization header. (as #pankajparkar has answered correctly before)
The reason why it simply works in the browser address bar is that the browser does this step automatically for you.

Related

Not getting json rest response in my AngularJS application

This has been frustrating me a bit. I have a restful services giving JSON data running on the link:
http://localhost:51133/API/SalesSystem/
So its running locally on my computer. I can get the data from this service with no problem using my WPF based interface.
Another service I am testing with is this one:
http://rest-service.guides.spring.io/greeting
But from my own service something seems to go wrong somehow and I cannot figure out what goes wrong. I have even tried just taking the full response and printing it. With the second service, I get a long list of data regarding the response, but with my own I still get nothing. As if the function was not used at all.
This is my Angular code:
angular.module('demo', [])
.controller('Hello', function ($scope, $http) {
$http.get('http://localhost:51133/api/salessystem/').
//http://rest-service.guides.spring.io/greeting
//http://localhost:51133/API/SalesSystem/
then(function (response) {
$scope.hello = 'hello';
$scope.district = response;
});
});
and this is my html code:
<!doctype html>
<html ng-app="demo">
<head>
<title>Hello AngularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
<script src="Scripts/hello.js"></script>
</head>
<body>
<div ng-controller="Hello">
<li>Id: <button>{{hello}}</button></li>
<li>Area: {{district}}</li>
<ul ng-repeat="obj in hello">
<li>Area: {{obj.area}}</li>
</ul>
<p>The ID is {{hello.Id}}</p>
<p>The content is {{hello.Area}}</p>
</div>
</body>
</html>
Can anyone see the problem? The spring rest service shows all kinds of data about the response and it also shows the button with "hello" inside it. But when I use my own service link it seems there is no $scope returned at all.
Oh, and this is the json returned when I just visit the link directly in the browser: (its an array of 3 districts)
[{"Id":1,"Area":"North Denmark","PrimarySalespersonID":1,"PrimarySalesperson":{"Id":1,"Name":"Tom B. Erichsen"},"SecondarySalespersons":null,"Stores":null},{"Id":2,"Area":"Southern Denmark","PrimarySalespersonID":2,"PrimarySalesperson":{"Id":2,"Name":"Eric B. Thomsen"},"SecondarySalespersons":null,"Stores":null},{"Id":3,"Area":"Eastern Denmark","PrimarySalespersonID":3,"PrimarySalesperson":{"Id":3,"Name":"Ben Anderson"},"SecondarySalespersons":null,"Stores":null}]

Mapping curl statement to $http.post

I am a beginner in angular js. I am experimenting with $http service in angularjs. I am accessing a web service. It returns expected response when using curl statement in ubuntu but is not succeeding when the parameter in curl is mapped to $http.post() parameter. Please take a look at my code for both curl and angularjs page. Please point me out my mistake and help me to resolve the issue.
curl --data "email=test#test5.com" HTTP://dummy.dummyplane.com/dummyservices/UserExists
Result:
{"Data":"123456","Success":true,"Exception":null}
Angularjs code
<!DOCTYPE html>
<html lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
</head>
<body ng-app="myapp">
<div ng-controller="registerController">
<button ng-click='Register()' style='margin-top:15px'>Register</button>
</div>
<script type="text/javascript">
var app = angular.module('myapp', []);
app.controller('registerController', function($scope, $http) {
$scope.Register = function() {
$http({
url:'http://tethys.dev.riekerinc.com/totalsolutions/UserExists/',
method:'POST',
data:{"email":"tina#test5.com"},
headers:{'Content-Type':'application/x-www-form-urlencoded'}
}).success(function(data){
//console.log(data)
alert("Success");
});
};
});
</script>
</body>
</html>
You set the content type to the correct value, but you don't tell angular to use a different serializer than the default one, so it still sends it in JSON format.
Use $httpParamSerializerJQLike, or simply send the data as a string:
data: 'email=tina#test5.com'

With 1.4 version of AngularJS, is it possible to create persistent cookies with $cookies?

With 1.4 version of AngularJS, is it possible to create persistent cookies with $cookies?
I want data to be stored once I login, for 7 days say. In version 1.3.X, it is not possible to set Expiration date even. But with 1.4, they have deprecated $cookieStore and set an option in $cookies for expiration date.
I want to know whether this one creates cookies for desired longer periods rather than I close the browser and everything is gone.
You can set the expires property on the $cookiesProvider to change the default behaviour of the $cookies service. $cookiesProvider is available with version 1.4. For more info, see here.
The code below do what you want. When you are writing the cookie you can tell the expiration date. You can close the browser and the cookie will remain active.
Setting expiry dates PREVENT it from being deleted when the browser is closed.
setting persistent cookies with javascript
<!DOCTYPE html>
<html ng-app="cookiesExample">
<head>
<meta charset="utf-8" />
<script src="https://code.angularjs.org/1.4.0-rc.2/angular.js"></script>
<script src="https://code.angularjs.org/1.4.0-rc.2/angular-cookies.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<script>
angular.module('cookiesExample', ['ngCookies'])
.controller('MainCtrl', ['$cookies', '$scope', function($cookies, $scope) {
// Retrieving a cookie
var favoriteCookie = $cookies.get('myFavorite');
$scope.name = (favoriteCookie) ? 'welcome back' : 'first time';
// Setting a cookie
var now = new Date();
now.setDate(now.getDate() + 7);
$cookies.put('myFavorite', 'oatmeal', {
expires: now
});
}]);
</script>
</body>
</html>

BTC Guild API Parsing Issue with AngularJS

I am trying to get some basic information from the BTC Guild API through AngularJS, but all it does is run in the error function and gives no output as to what the error is. Firebug shows nothing in the error object when breaking in that function. Any ideas?
jsfiddle link: http://jsfiddle.net/bX3ar/11/
javascript:
angular.module('BTCGuild', []);
function BTCGuildCtrl($scope, $http) {
$http.get('https://www.btcguild.com/api.php?api_key=').success(function (response) {
$scope.error = 'response:' + response;
$scope.unpaidRewards = response.user.unpaid_rewards;
}).error(function (error, status) {
$scope.error = 'error:' + error + status;
});
}
html:
<!doctype html>
<head>
<script type="text/javascript" src="http://code.angularjs.org/1.1.5/angular.min.js"></script>
<script type="text/javascript" src="btcguild.js"></script>
</head>
<html ng-app="BTCGuild">
<body>
<div ng-controller="BTCGuildCtrl">
<table>
<p>{{unpaidRewards}}</p>
<p>Error:{{error}}</p>
</table>
</div>
</body>
</html>
A couple of notes:
You're going to get a "Cross Origin Request" error. Here's a snippet of the response after fixing it:
OPTIONS https://www.btcguild.com/api.php?api_key= No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fiddle.jshell.net' is therefore not allowed access.
Take a look at these notes on how to properly format a JSFiddle for Angular: Frameworks & Extensions should be No Library - pure JS, and No wrap, in . Also, you'll want to put this under Fiddle Options: Body Tag <body ng-app="BTCGuild">
Here is the updated JSFiddle: http://jsfiddle.net/bX3ar/14/
If you can get through the CORs issue, you'll see this work. Or if you put in a fake response, you can see it display properly.

How to access cookies in AngularJS?

What's the AngularJS way to access cookies? I've seen references to both a service and a module for cookies, but no examples.
Is there, or is there not an AngularJS canonical approach?
This answer has been updated to reflect latest stable angularjs version. One important note is that $cookieStore is a thin wrapper surrounding $cookies. They are pretty much the same in that they only work with session cookies. Although, this answers the original question, there are other solutions you may wish to consider such as using localstorage, or jquery.cookie plugin (which would give you more fine-grained control and do serverside cookies. Of course doing so in angularjs means you probably would want to wrap them in a service and use $scope.apply to notify angular of changes to models (in some cases).
One other note and that is that there is a slight difference between the two when pulling data out depending on if you used $cookie to store value or $cookieStore. Of course, you'd really want to use one or the other.
In addition to adding reference to the js file you need to inject ngCookies into your app definition such as:
angular.module('myApp', ['ngCookies']);
you should then be good to go.
Here is a functional minimal example, where I show that cookieStore is a thin wrapper around cookies:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
</head>
<body ng-controller="MyController">
<h3>Cookies</h3>
<pre>{{usingCookies|json}}</pre>
<h3>Cookie Store</h3>
<pre>{{usingCookieStore|json}}</pre>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular-cookies.js"></script>
<script>
angular.module('myApp', ['ngCookies']);
app.controller('MyController',['$scope','$cookies','$cookieStore',
function($scope,$cookies,$cookieStore) {
var someSessionObj = { 'innerObj' : 'somesessioncookievalue'};
$cookies.dotobject = someSessionObj;
$scope.usingCookies = { 'cookies.dotobject' : $cookies.dotobject, "cookieStore.get" : $cookieStore.get('dotobject') };
$cookieStore.put('obj', someSessionObj);
$scope.usingCookieStore = { "cookieStore.get" : $cookieStore.get('obj'), 'cookies.dotobject' : $cookies.obj, };
}
</script>
</body>
</html>
The steps are:
include angular.js
include angular-cookies.js
inject ngCookies into your app module (and make sure you reference that module in the ng-app attribute)
add a $cookies or $cookieStore parameter to the controller
access the cookie as a member variable using the dot (.) operator
-- OR --
access cookieStore using put/get methods
This is how you can set and get cookie values. This is what I was originally looking for when I found this question.
Note we use $cookieStore instead of $cookies
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="http://code.angularjs.org/1.0.0rc10/angular-1.0.0rc10.js"></script>
<script src="http://code.angularjs.org/1.0.0rc10/angular-cookies-1.0.0rc10.js"></script>
<script>
angular.module('myApp', ['ngCookies']);
function CookieCtrl($scope, $cookieStore) {
$scope.lastVal = $cookieStore.get('tab');
$scope.changeTab = function(tabName){
$scope.lastVal = tabName;
$cookieStore.put('tab', tabName);
};
}
</script>
</head>
<body ng-controller="CookieCtrl">
<!-- ... -->
</body>
</html>
Angular deprecated $cookieStore in version 1.4.x, so use $cookies instead if you are using latest version of angular. Syntax remain same for $cookieStore & $cookies:
$cookies.put("key", "value");
var value = $cookies.get("key");
See the Docs for an API overview. Mind also that the cookie service has been enhanced with some new important features like setting expiration (see this answer) and domain (see CookiesProvider Docs).
Note that, in version 1.3.x or below, $cookies has a different syntax than above:
$cookies.key = "value";
var value = $cookies.value;
Also if you are using bower, make sure to type your package name correctly:
bower install angular-cookies#X.Y.Z
where X.Y.Z is the AngularJS version you are running.
There's another package in bower "angular-cookie"(without the 's') which is not the official angular package.
FYI, I put together a JSFiddle of this using the $cookieStore, two controllers, a $rootScope, and AngularjS 1.0.6. It's on JSFifddle as http://jsfiddle.net/krimple/9dSb2/ as a base if you're messing around with this...
The gist of it is:
Javascript
var myApp = angular.module('myApp', ['ngCookies']);
myApp.controller('CookieCtrl', function ($scope, $rootScope, $cookieStore) {
$scope.bump = function () {
var lastVal = $cookieStore.get('lastValue');
if (!lastVal) {
$rootScope.lastVal = 1;
} else {
$rootScope.lastVal = lastVal + 1;
}
$cookieStore.put('lastValue', $rootScope.lastVal);
}
});
myApp.controller('ShowerCtrl', function () {
});
HTML
<div ng-app="myApp">
<div id="lastVal" ng-controller="ShowerCtrl">{{ lastVal }}</div>
<div id="button-holder" ng-controller="CookieCtrl">
<button ng-click="bump()">Bump!</button>
</div>
</div>
http://docs.angularjs.org/api/ngCookies.$cookieStore
Make sure you include http://code.angularjs.org/1.0.0rc10/angular-cookies-1.0.0rc10.js to use it.
Add angular cookie lib : angular-cookies.js
You can use $cookies or $cookieStore parameter to the respective controller
Main controller add this inject 'ngCookies':
angular.module("myApp", ['ngCookies']);
Use Cookies in your controller like this way:
app.controller('checkoutCtrl', function ($scope, $rootScope, $http, $state, $cookies) {
//store cookies
$cookies.putObject('final_total_price', $rootScope.fn_pro_per);
//Get cookies
$cookies.getObject('final_total_price'); }
AngularJS provides ngCookies module and $cookieStore service to use Browser Cookies.
We need to add angular-cookies.min.js file to use cookie feature.
Here is some method of AngularJS Cookie.
get(key); // This method returns the value of given cookie key.
getObject(key); //This method returns the deserialized value of given
cookie key.
getAll(); //This method returns a key value object with all the
cookies.
put(key, value, [options]); //This method sets a value for given
cookie key.
remove(key, [options]); //This method remove given cookie.
Example
Html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular-cookies.min.js"></script>
</head>
<body ng-controller="MyController">
{{cookiesUserName}} loves {{cookietechnology}}.
</body>
</html>
JavaScript
var myApp = angular.module('myApp', ['ngCookies']);
myApp.controller('MyController', ['$scope', '$cookies', '$cookieStore', '$window', function($scope, $cookies, $cookieStore, $window) {
$cookies.userName = 'Max Joe';
$scope.cookiesUserName = $cookies.userName;
$cookieStore.put('technology', 'Web');
$scope.cookietechnology = $cookieStore.get('technology'); }]);
I have Taken reference from http://www.tutsway.com/simple-example-of-cookie-in-angular-js.php.
The original accepted answer mentions jquery.cookie plugin. A few months ago though, it was renamed to js-cookie and the jQuery dependency removed. One of the reasons was just to make it easy to integrate with other frameworks, like Angular.
Now, if you want to integrate js-cookie with angular, it is as easy as something like:
module.factory( "cookies", function() {
return Cookies.noConflict();
});
And that's it. No jQuery. No ngCookies.
You can also create custom instances to handle specific server-side cookies that are written differently. Take for example PHP, that convert the spaces in the server-side to a plus sign + instead of also percent-encode it:
module.factory( "phpCookies", function() {
return Cookies
.noConflict()
.withConverter(function( value, name ) {
return value
// Decode all characters according to the "encodeURIComponent" spec
.replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent)
// Decode the plus sign to spaces
.replace(/\+/g, ' ')
});
});
The usage for a custom Provider would be something like this:
module.service( "customDataStore", [ "phpCookies", function( phpCookies ) {
this.storeData = function( data ) {
phpCookies.set( "data", data );
};
this.containsStoredData = function() {
return phpCookies.get( "data" );
}
}]);
I hope this helps anyone.
See detailed info in this issue: https://github.com/js-cookie/js-cookie/issues/103
For detailed docs on how to integrate with server-side, see here: https://github.com/js-cookie/js-cookie/blob/master/SERVER_SIDE.md
Here's a simple example using $cookies. After clicking on button, the cookie is saved, and then restored after page is reloaded.
app.html:
<html ng-app="app">
<head>
<meta charset="utf-8" />
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular-cookies.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="appController as vm">
<input type="text" ng-model="vm.food" placeholder="Enter food" />
<p>My favorite food is {{vm.food}}.</p>
<p>Open new window, then press Back button.</p>
<button ng-click="vm.openUrl()">Open</button>
</body>
</html>
app.js:
(function () {
"use strict";
angular.module('app', ['ngCookies'])
.controller('appController', ['$cookies', '$window', function ($cookies, $window) {
var vm = this;
//get cookie
vm.food = $cookies.get('myFavorite');
vm.openUrl = function () {
//save cookie
$cookies.put('myFavorite', vm.food);
$window.open("http://www.google.com", "_self");
};
}]);
})();

Resources