每一个我对angular js都是陌生的,所以,我想使用 Angular概念,例如使用ngRoute进行路由,以满足我的要求。
这是我的js代码
var mainApp = angular.module("mainApp", ['ngRoute']);
mainApp.config(function($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'StudentController'
})
.when('/viewStudents', {
templateUrl: 'viewStudents.html',
controller: 'StudentController'
})
.otherwise({
redirectTo: '/home'
});
});
mainApp.controller('StudentController', function($scope) {
$scope.students = [
{name: 'Mark Waugh', city:'New York'},
{name: 'Steve Jonathan', city:'London'},
{name: 'John Marcus', city:'Paris'}
];
$scope.message = "Click on the hyper link to view the students list.";
});
这是我的index.html
**<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8">
<title>AngularJS Routing</title>
</head>
<body>
<div ng-app="mainApp">
<ng-view></ng-view>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28//angular-route.min.js"></script>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
这是home.html
<div class="container">
<h2> Welcome </h2>
<p>{{message}}</p>
<a href="#/viewStudents"> View Students List</a>
</div>
当我在浏览器中打开index.html时,它必须加载js代码中提到的home.html。
但是我在控制台中遇到以下错误
angular.js:8632 Access to XMLHttpRequest at 'file:///E:/battleField/angular/WebContent/WEB-INF/home.html' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
我的代码和运行页面的方式有什么问题。请帮助我摆脱这个我参考以下教程来获得它 https://www.journaldev.com/6225/angularjs-routing-example-ngroute-routeprovider
工作正常。 谢谢。
答案 0 :(得分:1)
之所以发生此错误,是因为您只是直接从浏览器中打开html文档。要解决此问题,您将需要从网络服务器调用页面并在localhost上访问它。使用Wamp Server或Apache,或者如果您具有nodejs设置,则使用http-server