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
Related
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 :/
I'm attempting to load a JSON file into my JavaScript file. However, I am at a loss at how to do so.
My app.js file:
var myApp = angular.module('myApp', []);
myApp.controller('MainCtrl', ['$scope', function ($scope) {
console.log("in here");
var jsonData = require('../test_data.json');
console.log(jsonData);
}]);
I have a test_data.json file in my project directory. The error above gives a "require is not defined", so it seems that I must install RequireJS? Is there another way to do so without installing any plugins?
Try using Angular's $http service and you'll have more control over the loading, errors, etc:
myApp.controller('MainCtrl', ['$scope', '$http', function ($scope, $http) {
console.log("in here");
$http.get('../test_data.json').success(function(data) {
console.log(data);
})
}]);
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 have an angular app with a directory structure
app
..views
....partials
......main.jade
......foo.jade
....index.jade
and routes defined like:
'use strict';
angular.module('myApp', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute',
'firebase',
'myApp.config'
])
.config(function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/', {
templateUrl: '/partials/main',
controller: 'MainCtrl'
})
.when('/foo/:fooName', {
templateUrl: '/partials/foo',
controller: 'FooCtrl'
})
.otherwise({
redirectTo: '/'
});
});
I'm using express on the server side and the relevant code is:
// server.js
app.configure('development', function(){
app.use(express.static(path.join(__dirname, '.tmp')));
app.use(express.static(path.join(__dirname, 'app')));
app.use(express.errorHandler());
});
app.configure('production', function(){
app.use(express.favicon(path.join(__dirname, 'public/favicon.ico')));
app.use(express.static(path.join(__dirname, 'public')));
});
app.get('/', routes.index);
app.get('/partials/:name', routes.partials);
//routes.js
exports.index = function(req, res){
res.render('index');
};
exports.partials = function(req, res){
var name = req.params.name;
res.render('partials/' + name);
};
The main route "/" loads fine and when i click to "/foo/bar" the partial view foo.jade loads as expected. However, when I try visiting "/foo/bar" directly in the URL i get a 404 response from Express "cannot GET /foo/bar" which makes sense since there's no route like this defined in express. However, I thought this was the whole point of defining the angular router..i.e. it's supposed to intercept this request and actually ask for "/partials/foo".
I tried adding
//redirect all others to the index (HTML5 history)
app.get('*', routes.index);
but it didnt solve the issue and seemed to be catching even the requests for static js assets and responding with the contents of index.html which is pretty bad.
I'm sure I'm doing something wrong. How can I fix things so that I can directly visit the URLs?
The reason routing is behaving like this is html5mode turned on.
Notice the line: $locationProvider.html5Mode(true);
You need to understand that when you try to access "/foo/bar" directly your browser sends HTTP GET request to this URL. When you try to access this url via link clicking, like you said, Angular is intercepting this action and calls History.pushState that only updates browser's link.
What you need to do in order to make html5mode routing work is implementing url rewrite. Every request has to be redirected to your index file that bootstraps AngularJS application, but this needs to be done on your server. Angular will render the desired page by itself.
Check out connect mod rewrite grunt task that does exacly that.
You can also you this middleware directly.