I'm trying to create a single page web application using ng-view but I'm unable to progress. There seems to be a problem loading in the html pages and I don't know what to do about it. Would anybody be able to identify what's wrong with my program?
The following files are contained in a directory called Example:
angular.js (v1.4.3)
angular-route.js (v1.4.3)
script.js
index.html
first.html
second.html
index.html
<!DOCTYPE html>
<html>
<head>
<script src="angular.js"></script>
<script src="angular-route.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="RoutingApp">
<div>
<h2>AngularJS Routing Example</h2>
<p>Jump to the first or second page</p>
<div ng-view></div>
</div>
</body>
</html>
script.js:
var app = angular.module('RoutingApp', ['ngRoute']);
app.config( [ '$routeProvider', function($routeProvider) {
$routeProvider
.when('/first', {
templateUrl: 'first.html'
})
.when('/second', {
templateUrl: 'second.html'
})
.otherwise({
redirectTo: '/'
});
}]);
first.html
<h2>This is the first page.</h2>
second.html
<h2>This is the second page.</h2>
From the Chrome debugging console:
XMLHttpRequest cannot load file:///C:/Users/d.n.harvey.macaulay/Desktop/Example/first.html. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
Error: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'file:///C:/Users/d.n.harvey.macaulay/Desktop/Example/first.html'.
at Error (native)
at file:///C:/Users/d.n.harvey.macaulay/Desktop/Example/angular.js:10514:11
at sendReq (file:///C:/Users/d.n.harvey.macaulay/Desktop/Example/angular.js:10333:9)
at serverRequest (file:///C:/Users/d.n.harvey.macaulay/Desktop/Example/angular.js:10045:16)
at processQueue (file:///C:/Users/d.n.harvey.macaulay/Desktop/Example/angular.js:14567:28)
at file:///C:/Users/d.n.harvey.macaulay/Desktop/Example/angular.js:14583:27
at Scope.$eval (file:///C:/Users/d.n.harvey.macaulay/Desktop/Example/angular.js:15846:28)
at Scope.$digest (file:///C:/Users/d.n.harvey.macaulay/Desktop/Example/angular.js:15657:31)
at Scope.$apply (file:///C:/Users/d.n.harvey.macaulay/Desktop/Example/angular.js:15951:24)
at HTMLBodyElement.<anonymous> (file:///C:/Users/d.n.harvey.macaulay/Desktop/Example/angular.js:12086:24)(anonymous function) # angular.js:12330 Error: [$compile:tpload] Failed to load template: first.html (HTTP status: undefined undefined)
http://errors.angularjs.org/1.4.3/$compile/tpload?p0=first.html&p1=undefined&p2=undefined
at angular.js:68
at handleError (angular.js:17530)
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 HTMLBodyElement.<anonymous> (angular.js:12086)
at HTMLBodyElement.eventHandler (angular.js:3271)
Thanks in advance.
It's because browsers don't allow to access local files through AJAX requests.
You need to serve your page using a web server (e.g. apache) and access the page with http://localhost/index.html
First of all your first or second page</p>
should have links in the following manner
first
also secondly, are you loading your template urls properly, Have a look at this post AngularJS writing an app with no server
Related
I am using express and node.js in backend and ejs templating engine in front-end. My app.js look like this
app.get('/book/:id', (req, res)=>{
var book_id = req.params.id;
console.log('this book :', book_id);
Book.findOne({
book_id
}).then((book)=>{
res.render('book.ejs', {book, title: "Book"});
}).catch((e)=>{
// console.log(e);
});
});
book.ejs file
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="books.js"></script>
</head>
<body style="font-family: arial">
<h1><%= title %></h1>
</body>
</html>
But when i route page to book/1234, I got following log in my server
this book : 1234
this book : jquery-3.3.1.min.js
this book : book.js
Why jquery-3.3.1.min.js and book.js are send to book/:id route? I am only sending book/1234 but jquery-3.3.1.min.js and book.js are also sent to server and causing error.
Browser console log is this
GET http://localhost:3000/book/jquery-3.3.1.min.js net::ERR_ABORTED 500 (Internal Server Error)
1234:1 Refused to execute script from 'http://localhost:3000/book/jquery-3.3.1.min.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
1234:6 GET http://localhost:3000/book/books.js net::ERR_ABORTED 500 (Internal Server Error)
1234:1 Refused to execute script from 'http://localhost:3000/book/books.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
Since script links have relative paths, they are loaded from current path, which is /book.
They should either have absolute paths:
<script type="text/javascript" src="/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="/books.js"></script>
Or base URL should be specified:
<base href="/">
You are using relative path in src attribute. Since you are serving the page from /books/<id>, if you use a relative path, browser will understand it as /books/(relative_path_of_resource) and so when it comes across those links it is sending a request to books/jquery.js and books/books.js
You should convert your link to point to the correct static path of the js files. Refer this link - https://expressjs.com/en/starter/static-files.html to see how to serve static files and once you set up the serving, you can change the links to /static/books.js and /static/jquery.js
I think that your book.ejs file is under the route of '/book'. if that so, you script tag like <script type="text/javascript" src="books.js"></script> will access the route of /book/book.js ,not your assets.
so you should set you src attribute like this /book.js and make sure you had made your assets accessible.
I have a strange problem with System JS when I'm playing around with Angular 2.
Everything works fine for a while, but seemingly random System JS can't find modules anymore...
I get this error message:
GET http://localhost:9000/angular2/platform/browser.js 404 (Not Found) # system.src.js:4891(anonymous function) # system.src.js:4891
GET http://localhost:9000/angular2/core.js 404 (Not Found) # system.src.js:4891
GET http://localhost:9000/angular2/router.js 404 (Not Found) # system.src.js:4891
GET http://localhost:9000/angular2/http.js 404 (Not Found) # system.src.js:4891
GET http://localhost:9000/angular2/core.js 404 (Not Found) # system.src.js:4891
GET http://localhost:9000/angular2/http.js 404 (Not Found) # system.src.js:4891
GET http://localhost:9000/angular2/src/facade/lang.js 404 (Not Found) # system.src.js:4891
GET http://localhost:9000/angular2/router.js 404 (Not Found) # system.src.js:4891
Sometimes it's more sometimes it's less errors...
The strangest thing is that after waiting a while and trying to refresh the page over and over, the app magically starts working again!
I use systemjs#0.19.20 and angular2#2.0.0-beta.3 (latest at the time).
Script section of index.html with SystemJS config look like this:
<script src="./node_modules/angular2/bundles/angular2-polyfills.js"></script>
<script src="./node_modules/es6-shim/es6-shim.min.js"></script>
<script src="./node_modules/systemjs/dist/system.js"></script>
<script>
//configure system loader
System.config({
defaultJSExtensions: true
});
//bootstrap the Angular2 application
System.import('dist/app').catch(console.log.bind(console));
</script>
<script src="./node_modules/rxjs/bundles/Rx.js"></script>
<script src="./node_modules/angular2/bundles/angular2.dev.js"></script>
<script src="./node_modules/angular2/bundles/http.dev.js"></script>
<script src="./node_modules/angular2/bundles/router.dev.js"></script>
Anyone recognize this problem?
Thanks!
It seems that your SystemJS isn't correct:
Do you use something like that in your HTML entry page:
<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="node_modules/rxjs/bundles/Rx.js"></script>
<script src="node_modules/angular2/bundles/angular2.dev.js"></script>
<script src="node_modules/angular2/bundles/router.dev.js"></script>
<script src="node_modules/angular2/bundles/http.dev.js"></script>
<script>
System.config({
packages: {
app: {
format: 'register',
defaultExtension: 'js'
}
}
});
System.import('app/boot')
.then(null, console.error.bind(console));
</script>
From what I see in your HTTP calls, I guess that there is something like that in your SystemJS configuration:
System.config({
packages: {
app: {
format: 'register',
defaultExtension: 'js'
},
angular2: {
format: 'register',
defaultExtension: 'js'
}
}
});
Maybe a long shot as I don't have the enough privileges to comment and ask for more information. Did you try checking if the file app.ts actually resides in dist/app?
I am trying to build simple routing app in angularjs. I have main index.html page with ng-view div and javascript code for routing. Also 2 simple html pages view2.html and view3.html placed in sub folder partials1.
I am getting below error. Please help.
Error: Access is denied.
Error: [$compile:tpload] Failed to load template: partials1/view3.html
http://errors.angularjs.org/1.3.15/$compile/tpload?p0=partials1%2Fview3.html
index.html:
<div data-ng-view></div>
<script src="angular.js"></script>
<script src="angular-route.js"></script>
<script type="text/javascript">
var demoApp = angular.module('demoApp', [ 'ngRoute' ]);
demoApp.controller('SimpleController', function($scope) {
$scope.customers = [ {
name : 'Jon Smith1',
city : 'Charlotte'
}, {
name : 'John Doe',
city : 'New York'
}, {
name : 'Jane Doe',
city : 'Jacksonville'
} ];
});
demoApp.config([ '$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {
templateUrl : 'partials1/view3.html',
controller : 'SimpleController'
}).when('/view2', {
templateUrl : 'partials1/view2.html',
controller : 'SimpleController'
}).otherwise({
redirectTo : '/view1'
});
} ]);
</script>
view2.html
<div class="container">33333333333333</div>
view3.html
<div class="container">33333333333333</div>
Error: Access is denied tells you that the template is not accessible. Try to open the template in your browser. Something like this: http://my_project/partials1/view3.html. To see the full URL which is used by your app, use a dubug console (XHR tab).
Error: [$compile:tpload] Failed to load template: xyz.html (HTTP status: 404 Not Found)
can be caused by below setting in web.config
<system.webServer>
<handlers>
<remove name="BlockViewHandler"/>
<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
This causes to block any direct request to the file in Views directory. Angular xhr request to this file is blocked by this.
Comment it out and see if things work. Use this with caution as it allows access to your files.
You can also check on this url for more responses: Error: $compile:tpload failed to load template Http status : 404
In my case, the issue is that I added Default Headers such as Accept = 'application/json'. So my routes suddenly stopped working, because those headers were not only applied to my $http.post calls, they were also applied to my Routing... ? Weird.
I had the same error, in my case the web server was written with node js and the uri to get views that were in the specified path with $stateProvider was not created, since for each view/template that is wanted to display an http request of type Xhr GET is made.
As the uri did not exist I obtained a 404 code and this made the browser got into callback that killed him. Make sure your server is returning the requested view. (Translated with google translate)
I am using webapp2 to build a webapp with angularjs. This is the directory structure.
|--test-app
|--lib
|--static
|--js
|--app.js
|--controller.js
|--lib
|--angular
|--angualr-bootstrap
|--index.html
|--app.yaml
|--mainapp.py
But when I try to load the js files in index.html
<!DOCTYPE html>
<html lang="en" ng-app="testApp">
<head>
<script src="/static/js/app.js"></script>
<script type="text/javascript" src="/static/js/controller.js"></script>
</head>
<body>
<div ng-controller="MainController">
IN MAIN
</div>
</body>
</html>
I get these errors:
GET http://localhost:8080/static/js/app.js (404 - file not found)
GET http://localhost:8080/static/js/controller.js (404 - file not found)
I cannot figure out why I am getting these errors.
Here is code for app.yaml
application: test-app
version: 1
runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: /.*
script: mainapp.app
libraries:
- name: webapp2
version: "2.5.2"
Here is code for mainapp.py
class Start(webapp2.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/html'
self.response.write(open('static/index.html').read())
app = webapp2.WSGIApplication([
('/', Start),
], debug=True)
You must explicitly declare the location of your static content in app.yaml:
handlers:
- url: /static
static_dir: static
handlers:
- url: /.*
script: mainapp.app
See docs for details:
Unlike a traditional web hosting environment, Google App Engine does not serve files directly out of your application’s source directory unless configured to do so.
URL handler path patterns are tested in the order they appear in app.yaml, from top to bottom. In this case, the /static pattern will match before the /.* pattern will for the appropriate paths.
I moved the index.html out of the static folder and then declared explicitly the static url, as said by #Selcuk. And it works nows.
For some reason, my angularjs module isn't loading correctly. I am pretty new to this and I've read a lot of tutorials, but I can't seem to get this working.
[17:22:36.338] Error: [$injector:modulerr] Failed to instantiate module wc2013mongoMod due to:
[$injector:nomod] Module 'wc2013mongoMod' 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 have found this question, which appears to be a very close description to my problem: AngularJS: Uncaught Error: [$injector:modulerr] Failed to instantiate module?
It suggests re-arranging the order in which the scripts are included. I've tried to put the scripts at the end of the body, no luck. I've also tried to put them inside the <head> element, but still no luck. What am I doing wrong here?
I am using Jade, but the resulting HTML looks like this:
<!DOCTYPE html>
<html ng-app="wc2013mongoMod">
<head>
<title>World Cup 2014 MongoDB Experiment Project</title>
<link rel="stylesheet" href="/stylesheets/style.css">
<script src="js/angular/angular.js"></script><script src="js/main.js"></script>
</head>
<body>
<h1>World Cup 2014 MongoDB Experiment Project</h1>
<p>Welcome to World Cup 2014 MongoDB Experiment Project</p>
<div ng-controller="teamCtrl">
<p>Angular JS Controller</p>
</div>
</body>
</html>
The javascript looks like this:
console.log("loaded main.js");
var myApp = angular.module('wc2014mongoMod',[]);
myApp.service('teamService', function($http) {
//delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function(callbackFunc) {
$http({
method: 'GET',
url: '/api'
//params: 'limit=10, sort_by=created:desc',
//headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
}).success(function(data){
// With the data succesfully returned, call our callback
//callbackFunc(data);
console.log("data received");
console.log(data);
}).error(function(){
alert("error");
});
}
});
myApp.controller('teamCtrl', function($scope, teamService) {
$scope.data = null;
console.log("we're in the controller");
teamService.getData(function(dataResponse) {
$scope.data = dataResponse;
});
});
Check the difference. 2013 vs 2014.
<html ng-app="wc2013mongoMod">
and
var myApp = angular.module('wc2014mongoMod',[]);
You should spot the error given these two lines:
<html ng-app="wc2013mongoMod">
..
var myApp = angular.module('wc2014mongoMod',[]);
wc2013mongoMod !== wc2014mongoMod