I'm trying run this code:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Exemple 06</title>
</head>
<body>
<!-- Diretiva ng-repeat -->
<div ng-controller="MyController">
<a ng-href="#/">Page 1</a> | <a ng-href="#/p2">Page 2</a>
<div ng-view="#/p2"></div>
</div>
<script src="js/angular.js"></script>
<script src="js/angular-route.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function($routeProvider){
$routeProvider
.when('/' , {controller: 'MyController', templateUrl: 'p1.html'})
.when('/p2', {controller: 'MyController', templateUrl: 'p2.html'})
.otherwise({ redirectTo: '/'});
});
myApp.controller('MyController', function($scope){
$scope.nomes = [
{id: 1, nome: 'Arthur'},
{id: 2, nome: 'Portos'},
{id: 3, nome: 'Aramis'}
];
});
</script>
</body>
but the error below occur:
XMLHttpRequest cannot load file:///home/93579551515/Desktop/Angular/p1.html. Cross origin requests are only supported for HTTP.
I don't want to run it on a webserver.
CORS requests may only use the HTTP or HTTPS URL scheme, but the URL specified by the request is of a different type. This often occurs if the URL specifies a local file, using the file:/// scheme.
Just change the url to http://localhost instead of localhost . If you open the html file from local, you should create a local server to serve that html file, the simplest way is using Web Server for Chrome . That will fix the issue. Save this answer.
The CORS mechanism supports secure cross-origin requests and data transfers between browsers and servers. Modern browsers use CORS in APIs such as XMLHttpRequest or Fetch to mitigate the risks of cross-origin HTTP requests.
Solution 1: Configure the Backend to Allow CORS The basic requirement is to add Access-Control-Allow-Origin to the response header to specify the origin that is allowed to access resources from the server. This will allow https://domain-a.com to make a cross-origin request to your server.
You can add templates such as p1.html
and p2.html
in your index.html
by putting them inside script
tags, as mentioned in the docs.
<script type="text/ng-template" id="p1.html">
This is the content of the template
</script>
Then angular
will no longer need to make AJAX requests to fetch them.
Do note that these script
elements must appear after ng-app
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With