I'm trying to set a header to send an access token on every request. This is what I have tried:
.factory("TokenRestangular", "StorageService", function (Restangular, StorageService) {
return Restangular.withConfig(function (RestangularConfigurer) {
// Set access token in header.
RestangularConfigurer.setDefaultHeaders({Authorization:'Bearer '+ StorageService.get("access_token")});
RestangularConfigurer.setBaseUrl('/api');
});
})
I get the error:
Error: [ng:areq] http://errors.angularjs.org/1.2.19/ng/areq?p0=fn&p1=not%20aNaNunction%2C%20got%string
at Error (native)
at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js:6:450
at Bb (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js:19:68)
at Ua (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js:19:155)
at rc (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js:32:423)
at Object.d [as invoke] (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js:34:398)
at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js:36:288
at c (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js:34:305)
at d (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js:35:6)
at Object.instantiate (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js:35:165)
I think your factory function has one too many parameter passed, try this:
.factory("TokenRestangular", function (Restangular, StorageService) {
return Restangular.withConfig(function (RestangularConfigurer) {
// Set access token in header.
RestangularConfigurer.setDefaultHeaders({Authorization:'Bearer '+ StorageService.get("access_token")});
RestangularConfigurer.setBaseUrl('/api');
});
})
or
.factory("TokenRestangular", ["Restangular", "StorageService", function (Restangular, StorageService) {
return Restangular.withConfig(function (RestangularConfigurer) {
// Set access token in header.
RestangularConfigurer.setDefaultHeaders({Authorization:'Bearer '+ StorageService.get("access_token")});
RestangularConfigurer.setBaseUrl('/api');
});
}])
if you want to have safe minification code.
Related
when i submit signup form using postman it works fine, but when i try to submit using the below code it shows some error, im unable to figure it out, anyone please help me?
.controller('RegisterCtrl', function($scope, AuthService, $state, $http) {
$scope.user = {
name: '',
mobile:'',
email:'',
password:''
};
$scope.signup = function() {
$http.post("http://localhost:8080/api/signup", $scope.user, {headers: {'Content-Type': 'application/json'} })
.then(function (response) {
return response;
});
};
})
when i inspect chrome browser it logs the below error:
angular.js:14362 Error: Unexpected request: POST http://localhost:8080/api/signup
No more request expected
at $httpBackend (https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-mocks.js:1402:9)
at sendReq (http://localhost:3000/bower_components/angular/angular.js:12178:9)
at serverRequest (http://localhost:3000/bower_components/angular/angular.js:11930:16)
at processQueue (http://localhost:3000/bower_components/angular/angular.js:16689:37)
at http://localhost:3000/bower_components/angular/angular.js:16733:27
at Scope.$eval (http://localhost:3000/bower_components/angular/angular.js:18017:28)
at Scope.$digest (http://localhost:3000/bower_components/angular/angular.js:17827:31)
at ChildScope.$apply (http://localhost:3000/bower_components/angular/angular.js:18125:24)
at HTMLInputElement.<anonymous> (http://localhost:3000/bower_components/angular/angular.js:26813:23)
at HTMLInputElement.dispatch (http://localhost:3000/bower_components/jquery/dist/jquery.js:4435:9) Possibly unhandled rejection: {}(anonymous function) # angular.js:14362(anonymous function) # angular.js:10859processChecks # angular.js:16715$eval # angular.js:18017$digest # angular.js:17827$apply # angular.js:18125(anonymous function) # angular.js:26813dispatch # jquery.js:4435elemData.handle # jquery.js:4121
As already pointed out, you're lacking a lot of important details in your description. My best guess is that your endpoint is expecting your user object to be named "user", in which case your post call should look more like the following:
$http.post(
"http://localhost:8080/api/signup",
{ user: $scope.user },
);
I made this simple factory returning a $resource:
app.factory('OusService', function ($resource,BASE_API) {
var res;
res = $resource(BASE_API+'/ou/:ouId',null,{
update: {
method: 'PUT' // this method issues a PUT request
}
});
return res;
});
Then I'm using that $resource in a controller called 'navCtrl' :
app.controller('navCtrl', ["$scope","$localStorage","OusService", function ($scope,$localStorage,OusService) {
var navOrg = $localStorage.navOrg;
OusService.query({ouId: navOrg.ou_id}).$promise.then(function(data){
console.log(data);
}, function(error) {
console.log(error);
});
}]);
That code is completely crashing but if I remove '{ouId: navOrg.ou_id}' the code is executed but the query doesn't contain the required parameter. I tried without a promise, with a callback, withtout a callback nor a promise. The code is always crashing with parameter.
I also tried defining default parameters in the factory.
Error :
TypeError: V is not a function
at http://10.0.0.145:8003/layout1/assets/js/app.min.js:34:14237
at forEach (http://10.0.0.145:8003/layout1/assets/js/app.min.js:10:14316)
at C.setUrlParams (http://10.0.0.145:8003/layout1/assets/js/app.min.js:34:14122)
at Function.l.(anonymous function) [as query] (http://10.0.0.145:8003/layout1/assets/js/app.min.js:34:12722)
at new <anonymous> (http://10.0.0.145:8003/layout1/assets/js/controllers/navCtrl.js:13:16)
at Object.invoke (http://10.0.0.145:8003/layout1/assets/js/app.min.js:11:16221)
at extend.instance (http://10.0.0.145:8003/layout1/assets/js/app.min.js:13:8182)
at nodeLinkFn (http://10.0.0.145:8003/layout1/assets/js/app.min.js:12:11139)
at compositeLinkFn (http://10.0.0.145:8003/layout1/assets/js/app.min.js:12:2680)
at http://10.0.0.145:8003/layout1/assets/js/app.min.js:12:1389 <nav data-ng-include=" 'assets/views/partials/nav.html' " class="ng-scope" data-ng-animate="1">
EDIT :
I updated angularjs from 1.5.7 to 1.5.11 and the problem has been resolved.
thank you
to use like this .. have you tried something like:
app.factory('OusService', function ($resource,BASE_API) {
var res;
res = $resource(BASE_API+'/ou/:ouId',{'#ouId':ouId},{
query: {
method: 'GET',isArray:true // or false if return an object
}
});
return res;
});
And then use it as you want
app.controller('navCtrl', ["$scope","$localStorage","OusService", function ($scope,$localStorage,OusService) {
var navOrg = $localStorage.navOrg;
OusService.query({ouId: navOrg.ou_id}).$promise.then(function(data){
console.log(data);
}, function(error) {
console.log(error);
});
}]);
I do not believe that the $resource query method accepts an argument. Rather, it returns an array of results. If you want to pass an id in I would suggest using get
OusService.get({ouId: navOrg.ou_id}).$promise.then(function(data){
console.log(data);
}, function(error) {
console.log(error);
});
Also, try updating your resource to the following:
app.factory('OusService', ['$resource', 'BASE_API',
function($resource, BASE_API) {
var res;
res = $resource(BASE_API + '/ou/:ouId', {ouId: #ouId}, {
update: {
method: 'PUT'
}
});
return res;
}
]);
The key changes to note being: {ouId: #ouId} as well as ['$resource', 'BASE_API',
I want to use request interceptor in my app to add verify code into requests (for CSRF protection). My code looks like this now:
$httpProvider.interceptors.push(function($q, $injector, AppConst) {
return {
request: function(request) {
var VerifyCodeService = $injector.get('VerifyCodeService');
var verifyCodeUrl = AppConst.apiUrl + '/app/verifyCode'
if(request.url!=verifyCodeUrl && request.data!=undefined){
VerifyCodeService.getCode()
.then(function(data) {
if (AppConst.serviceResponseOk==data.result) {
request.data.verifyCode = data.verifyCode;
return request;
} else {
console.log('error');
return request;
}
}, function(error) {
console.log('error:' + error);
return request;
});
} else {
return request;
}
}
};
});
But for some reason I keep getting this error:
TypeError: Cannot read property 'headers' of undefined
at serverRequest (angular.js:10028)
at processQueue (angular.js:14567)
at angular.js:14583
at Scope.$eval (angular.js:15846)
at Scope.$digest (angular.js:15657)
at Scope.$apply (angular.js:15951)
at done (angular.js:10364)
at completeRequest (angular.js:10536)
at XMLHttpRequest.requestLoaded (angular.js:10477)
Anyone knows whats happening?
If I read this right, you are making a XHR which triggers another XHR to get the CSRF token and add it to the original request's data object. I think the issue is the second XHR. This second request is async just like the first, so you can't just return from the then method.
Try returning the promise generated by your second XHR in your if statement (which is resolved in the inner then invocation after the second XHR by return request;).
if(request.url!=verifyCodeUrl && request.data!=undefined){
var secondXhr = VerifyCodeService.getCode()
.then(function(data) {
if (AppConst.serviceResponseOk==data.result) {
request.data.verifyCode = data.verifyCode;
return request;
} else {
console.log('error');
return request;
}
}, function(error) {
console.log('error:' + error);
return request;
});
return secondXhr;
} else {
return request;
}
From the Interceptors section of the Angular docs (bolding added):
request: interceptors get called with a http config object. The
function is free to modify the config object or create a new one. The
function needs to return the config object directly, or a promise
containing the config or a new config object.
On a different note, it looks like you are introducing a significant delay into each XHR since you are essentially blocking each request until the token is returned.
A different implementation where each response returns the new token for the next request in a header could work (as long as you don't have concurrent requests(!)), or CSRF token per page load (if you have full page reloads) might be options. I'm sure there are suggestions on the internets if you want to make that change.
I am playing around with the MEAN stack. I have created a rest service to delete from mongo db which works fine but When I try to use angular Factory method and call it I get the above error
myApp.factory('methodFactory', ['$http', function ($http) {
return {
//id becomes undefined over here
removeContact:function($http, id){
//TODO add URL
var url = '/contactlist/'+id;
return $http({
method: 'DELETE',
url: url
});
}
};
}]);
myApp.controller('AppControl', ['$scope','$http','methodFactory', function($scope,$http,methodFactory) {
$scope.remove = function(id) {
console.log(id); //able to print correct id
methodFactory.removeContact(id).success(function(response){
console.log("remv"+response);
refresh();
});//tthiss throws the error
//this rest service works properly.
/*$http.delete('/contactlist/'+id).success(function(response){
console.log("remv"+response);
refresh();
});*/
};
};
This what node server looks like
app.delete('/contactlist/:id',function(req,res) {
var id = req.params.id;
console.log(id);
db.contactlist.remove({_id:mongojs.ObjectId(id)},function(err,doc){
res.json(doc);
});
console.log("exiting delete")
});
I am not sure if factory could be one of the way to call a rest service. What could cause the problem ?
Error
TypeError: string is not a function
at Object.removeContact (http://localhost:3000/controllers/controller.js:10:20)
at l.$scope.remove (http://localhost:3000/controllers/controller.js:85:23)
at hb.functionCall (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js:198:426)
at Cc.(anonymous function).compile.d.on.f (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js:215:74)
at l.$get.l.$eval (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js:126:193)
at l.$get.l.$apply (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js:126:419)
at HTMLButtonElement.<anonymous> (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js:215:126)
at HTMLButtonElement.c (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js:32:363)
Your removeContact method needs two parameters:
removeContact:function($http, id) ...
but you call it with only one:
methodFactory.removeContact(id) ...
Id is a string, I suppose, but it it will be assigned to the first parameter of the function $http, what must be executable according the code you provided.
I'm testing $firebaseSimpleLogin authentication.
I did set up oAuth accounts for Google, Facebook and Twitter, and them all work very smootly.
I only noticed a little issue (I can't tell if it's a real problem...): if you forget (or voluntarily avoid) enabling an origin domain (in firebaseio.com console), the authentication correctly fails, but no error is returned:
app.factory('Auth', function ($firebaseSimpleLogin) {
var ref = new Firebase(FIREBASE_URL);
var auth = $firebaseSimpleLogin(ref);
var provider = 'google'; // any social provider will fit
auth.$login(provider, {
rememberMe: true,
scope:
(provider === 'google') ?
'https://www.googleapis.com/auth/userinfo.profile' :
(provider === 'facebook') ? 'email' : null,
preferRedirect: false
}).then(
function (authUser) {
console.info('user authenticated');
},
function (error) {
/* ======================================================
* YOU DON'T GET HERE IF CURRENT DOMAIN IS NOT ENABLED...
* ====================================================== */
console.error('social login with ' + provider +
' provider failed: ' + error.message);
}
);
});
Is this a bug?
UPDATE:
#HarishR: do you mean something like this?
auth.$login(provider, {}
).then(
function (success) {},
function (error) {}
).catch(error) {
console.error('social login with ' + provider +
' provider failed: ' + error);
};
It gives syntax error...
For #HashirR this is the error details:
Uncaught SyntaxError: Unexpected token { auth.js:94
Error: [ng:areq] Argument 'AuthCtrl' is not a function, got undefined
http://errors.angularjs.org/1.2.16/ng/areq?p0=AuthCtrl&p1=not%20aNaNunction%2C%20got%20undefined
at http://0.0.0.0:9000/bower_components/angular/angular.js:78:12
at assertArg (http://0.0.0.0:9000/bower_components/angular/angular.js:1443:11)
at assertArgFn (http://0.0.0.0:9000/bower_components/angular/angular.js:1453:3)
at http://0.0.0.0:9000/bower_components/angular/angular.js:7131:9
at http://0.0.0.0:9000/bower_components/angular/angular.js:6538:34
at forEach (http://0.0.0.0:9000/bower_components/angular/angular.js:330:20)
at nodeLinkFn (http://0.0.0.0:9000/bower_components/angular/angular.js:6525:11)
at compositeLinkFn (http://0.0.0.0:9000/bower_components/angular/angular.js:5986:15)
at publicLinkFn (http://0.0.0.0:9000/bower_components/angular/angular.js:5891:30)
at link (http://0.0.0.0:9000/bower_components/angular/angular.js:19396:38)