Cross origin requests are only supported for HTTP
Asked Answered
F

3

10

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.

Fosque answered 7/11, 2013 at 21:42 Comment(3)
You can start a webserver locally as easily as python -mSimpleHTTPServer and then point your browser to localhost:8000/index.html.Lindalindahl
out of curiosity .. why don't you want to run a webserver?Athene
Run it in Brackets (brackets.io), it will work.Spade
L
30

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.

Lindalindahl answered 7/11, 2013 at 22:3 Comment(2)
It would be cool if I could make a script to collect all my view files and inject them in such script tags in the bottom of the main page. Does anyone know if such a script exists or how would I go about making it?Gusto
I receive this error when I use templates like this, the templates still function correctly, but it spams errors to the console.Ferocity
O
1

I've got the same trouble in Chrome, if you are using Chrome, you can disable same origin policy in Chrome. Starting the Chrome runs:

$ google-chrome --disable-web-security

Here's more detail.

Olnek answered 31/8, 2014 at 7:10 Comment(0)
G
0

Route provider uses http protocol that's why if you will run this code directly from folder, you will get cross origin issue.

Keep your folder on a server like localhost/route and run it.

Provide reference path like templateUrl: '/p1.html'

Gonococcus answered 10/7, 2017 at 5:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.