I am trying to have a HTTP interceptor that adds a token as a http header before every request to the server.
app.factory('httpRequestInterceptor',
['$rootScope', function($rootScope)
{
return {
request: function($config) {
if( $rootScope.token)
{
$config.headers['auth-token'] = $rootScope.token;
}
return $config;
}
};
}]);
Above, is my interceptor which looks okay to me. I then during the config state push this interceptor to the http provider, as you can see below.
app.config(function ($routeProvider, $httpProvider) {
$routeProvider
.when(...)
.otherwise({
redirectTo: '/'
});
$httpProvider.interceptors.push('httpRequestInterceptor');
});
Now when looking at my browser console log I get an error saying:
"Unknown provider: httpRequestInterceptorProvider <- httpRequestInterceptor <- $http <- defaultErrorMessageResolver"
It seems it can't resolve the dependency for the interceptor httpRequestInterceptor. Have I defined it wrong?
Thanks and appreciate any help!
Sorry, Was a silly mistake on my end, I forgot to include the factory in my index.html :/
Related
app.js
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'ngCordova', 'ngCookies'])
.run(function ($ionicPlatform) {
$ionicPlatform.ready(function () {
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
StatusBar.styleLightContent();
}
});
})
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('HomePage', {
url: '/HomePage/:id',
templateUrl: 'templates/HomePage.html',
controller: 'HomePageCtrl'
})
.state('login', {
url: '/login',
templateUrl: 'templates/Login.html',
controller: 'LoginCtrl'
});
$urlRouterProvider.otherwise('/login');
});
controllers.js
angular.module('starter.controllers', [])
.controller('LoginCtrl', function ($scope, LoginService, $ionicPopup, $state, $location, $http, $cookieStore) {
$cookieStore.put('mycookie', 'cookie value');
var favoriteCookie = $cookieStore.get('mycookie');
alert(favoriteCookie);
})
Question:
I am new for Angular JS Ionic.I am trying to use cookie in angularjs.
When i use $cookieStore
I get below exception:
Exception:
Uncaught Error: [$injector:modulerr] Failed to instantiate module starter due to:
Error: [$injector:modulerr] Failed to instantiate module ngCookies due to:
Error: [$injector:nomod] Module 'ngCookies' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
I added ngCookies to angular.module however it did not work for me.
Where i miss exactly ? How can i use cookie in angular js.
Any help will be appreciated.
Thanks.
I find that $cookies is not working in an Cordova/Phonegap app since the pages are served as a file URL. In an normal desktop browser it is also not working if you serve the pages from the filesystem - it's working when served via a server or localhost.
So I get to the assumption that angular $cookies don't work for Cordova apps.
Maybe theres a workaround for that? I just don't know, maybe someone nows an answer.
probably you have missed to add angular-cookies.js file
If so add it.
My angularjs example app is running fine in my netbeans ide based local server. But when I moved the application to nginx server it gives me the following error in the browser.
Error: [$compile:tpload] Failed to load template: views/login.html
http://errors.angularjs.org/1.3.15/$compile/tpload?p0=views%2Flogin.html
at REGEX_STRING_REGEXP (angular.js:63)
at handleError (angular.js:16133)
at processQueue (angular.js:13248)
at angular.js:13264
at Scope.$get.Scope.$eval (angular.js:14466)
at Scope.$get.Scope.$digest (angular.js:14282)
at Scope.$get.Scope.$apply (angular.js:14571)
at done (angular.js:9698)
at completeRequest (angular.js:9888)
at XMLHttpRequest.requestLoaded (angular.js:9829)
My app.js
appModule
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/',
{
controller: 'loginController',
templateUrl: 'views/login.html'
})
.when('/main',
{
controller: 'dashboardController',
templateUrl: 'views/dashboard.html'
})
.otherwise({redirectTo: '/'});
}])
If you use node.js, try this
app.use(express.static(path.join(__dirname,'yourFolder/invoices')));
I came to find out that my issue was regarding Default $http Headers. I had just recently added a default header for Authorization, and a default Accept for application/json.
SURPRISE!!! It turns out that those $http headers are NOT only applied to $http calls you make to your endpoints... but also to every call made that pulls your Routing html files. And since html files will explode if using those headers, the whole thing fails.
I simply stopped setting the Default $http headers, and wrote a side service that my microservice calls would use since they need app/json. Then my Angular Routing calls went back to using standard headers.
I am using $routeProvider service in my angular js but problem is on templateURl it provides me error
from server here is the error what i received
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
angular.js:11594 Error: [$compile:tpload] Failed to load template: /Testing/TestCompleted
and here is my angular code for app.js
var app = angular.module('app', ['ngRoute']);
app.controller('CreateController', CreateController);
app.config(function ($routeProvider) {
$routeProvider
.when('/',
{
templateUrl: "/Testing/TestCompleted",
controller:"AppCtrl"
})
});
app.controller("AppCtrl",function ($scope) {
$scope.newmodel = {
}
});
I found the solution the view is only returned by server by using route we can only get html view not cshtml because that is provided when action is called.
The url is giving a ERROR 500. This is that there is something wrong in de code of the page. Please attach your debugger and go to the url "/Testing/TestCompleted" with a browser and check what is wrong.
Edit:
If the url is really the right one. Please try the following:
angular.module('app', ['ngRoute'])
.controller("AppCtrl",function ($scope) {
$scope.newmodel = {}
})
.config(function ($routeProvider) {
$routeProvider
.when('/',
{
templateUrl: "/Testing/TestCompleted",
controller:"AppCtrl"
})
});
So that the controller is registerd before you do your config as in the example from Angular (https://docs.angularjs.org/api/ngRoute/service/$route).
The address of the template is likely wrong. I never had to use a format such as '/....' .
You probably want 'Testing/TestCompleted' if the directory Testing is at the root of your project (or './Testing/TestCompleted' both should work).
EDIT:
In any case you are probably using an html file for the template, with an extension .html . So use 'Testing/TestCompleted.html' for instance.
I'm using angularjs-seed app and I'm trying to get JSON response from server (MarkLogic) using $http. I've been on it for 3 days tried every response from other similar stackoverflow answers but not able to get it working. Please help!
The browser returns this:
XMLHttpRequest cannot load http://sreddy:8003/v1/search?format=json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access.
Here's my app code
app.js
'use strict';
// Declare app level module which depends on filters, and services
var app = angular.module('myApp', [
'ngRoute',
'myApp.filters',
'myApp.services',
'myApp.directives',
'myApp.controllers'
]);
app.config(['$routeProvider', '$httpProvider', function($routeProvider, $httpProvider) {
$routeProvider.when('/view1', {templateUrl: 'partials/partial1.html', controller: 'MyCtrl1'});
$routeProvider.when('/view2', {templateUrl: 'partials/partial2.html', controller: 'MyCtrl2'});
$routeProvider.otherwise({redirectTo: '/view1'});
// to avoid CORS
$httpProvider.defaults.withCredentials = true;
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);
controllers.js
'use strict';
/* Controllers */
var app = angular.module('myApp.controllers', []);
app.controller('MyCtrl1', ['$scope', 'dataService', function($scope, dataService) {
$scope.test = "test";
$scope.data = null;
dataService.getData().then(function (dataResponse) {
$scope.data = dataResponse;
});
console.log($scope.data);
}]);
app.controller('MyCtrl2', [function() {
console.log("from MyCtrl2");
}]);
services.js
'use strict';
/* Services */
// Demonstrate how to register services
// In this case it is a simple value service.
var app = angular.module('myApp.services', []);
app.value('version', '0.1');
app.service('dataService', function($http) {
this.getData = function() {
// $http() returns a $promise that we can add handlers with .then()
return $http({
method: 'GET',
url: 'http://sreddy:8003/v1/search?format=json'
});
}
});
useXDomain is not a thing.
You are indeed having a same-origin problem. In order for your request to work, you will need to change your headers on the request. Since you are making a simple GET request, you should be able to do it, provided it's a simple request. Your content-type is likely what is flagging the request as a CORS request.
Usually - this can be fixed by setting your content-type header to application/x-www-form-urlencoded, multipart/form-data, or text/plain, like this:
$http({
method: 'GET',
url: 'http://sreddy:8003/v1/search?format=json',
headers: {'Content-Type':'text/plain'} //or whatever type
});
Or - you can set up an interceptor and add headers to all requests meeting some criteria.
For not-simple requests, which may get preflighted, you will need to work more with the request headers in addition to ensure response headers satisfy the preflight request. If you don't have access to the server (to set response headers), you will have to work within their allowed parameters. Here is some more info on CORS.
You need to run an http server - simplest way is using python
from the main directory of the project...
python3 -m http.server 8080
Then go to the url localhost:8080/index.html and you'r golden !
I solved this issues by using express.js as a proxy server which also enables me to serve static content usinf the proxy
OK I'm officially bald now, after having been streching my hair out with this infamous problem: The minfied AngularJS app just doesn't work, with this error thown out:
Error: [$injector:unpr] Unknown provider: aProvider <- a
http://errors.angularjs.org/1.2.6/$injector/unpr?p0=aProvider%20%3C-%20a
at http://localhost/my-app/dist/scripts/1bde0e2e.vendor.js:4:11492
at http://localhost/my-app/dist/scripts/1bde0e2e.vendor.js:4:26946
at Object.c [as get] (http://localhost/my-app/dist/scripts/1bde0e2e.vendor.js:4:26250)
at http://localhost/my-app/dist/scripts/1bde0e2e.vendor.js:4:27041
at c (http://localhost/my-app/dist/scripts/1bde0e2e.vendor.js:4:26250)
at Object.d [as invoke] (http://localhost/my-app/dist/scripts/1bde0e2e.vendor.js:4:26496)
at http://localhost/my-app/dist/scripts/1bde0e2e.vendor.js:9:910
at Object.f [as forEach] (http://localhost/my-app/dist/scripts/1bde0e2e.vendor.js:4:11927)
at http://localhost/my-app/dist/scripts/1bde0e2e.vendor.js:9:856
at j (http://localhost/my-app/dist/scripts/1bde0e2e.vendor.js:5:27235)
Lots of other people had this problem as well, but looks like it could be fixed by declaring dependencies as an array instead of bare function parameters, like this:
angular.module('my-app').controller('LoginCtrl', [ '$scope', 'HttpService', function($scope, HttpService) { ... }]);
instead of this:
angular.module('my-app').controller('LoginCtrl', function($scope, HttpService) { ... });
But it doesn't work in my case. I checked all of my scripts (coffee and generated javascripts as well), they all use the proper array-style declaration.
The problem doesn't come from extra packages apparently. I tried moving all extra package references out of <!-- bower:js --> block (so that they are not minified by grunt), yet the problem still remains. Which means, it's my code to blame... But then again, I've tried the (seems to be) only fix available, to no avail.
Any hint, even on how to properly debug this?
Thanks in advance!
Finally I've found the problem. And yes, it's a DI bug which I missed.
To all who may be suffering from the same headache: array-format declaration must be done in $routeProvider's resolve options as well. In my case (CoffeeScript ahead):
app.config (['$routeProvider', ($routeProvider) ->
$routeProvider
.when '/',
templateUrl: 'views/main.html'
controller: 'MainCtrl'
resolve:
groups: ['GroupService', (GroupService) -> # I MISSED THIS
return GroupService.getAll()
]
entries: ['EntryService', (EntryService) -> # AND THIS
return EntryService.getAll()
]
# ...
])
Hope this helps!
This behaviour could come if you use implicit injection, instead of explicit declaring your dependencies. In my experience I faced this kind of problem with particular kind of Angular.js services that return instantiable class (for example to create abstract controller Classes or some other particular cases).
For example: AbstractBaseControllerClass
During minification I had the same problem. I solved using internal declaration of dependency injection.
Hope this helps
For the ones that doesn't like CoffeeScript.
I just took some of my code and put it in.
$stateProvider
.state('screen', {
url: '/user/',
templateUrl: 'user.html',
controller: 'UserController',
controllerAs: 'user',
location: "User",
resolve: ['$q', 'UserService', '$state', '$timeout', authenticateUser
]
})
function authenticateUser($q, UserService, $state, $timeout) {
UserService.getLoginStatus().then(function () {
if (UserService.user) {
console.log("is user");
return $q.when();
} else {
console.log("not user");
$timeout(function () {
// This code runs after the authentication promise has been rejected.
// Go to the log-in page
$state.go('login')
});
return $q.reject()
}
});
}