Does Angular need a web server to run? So would Angular work if I give browser a url of a local file?

All we need is an easy explanation of the problem, so here it is.

By this I mean I have read that Angular allows mock up data to be used so that RESTFul apis need not be wired up. I can think of a use case where a UX designer need only look at the cosmetics and need not hook up to a web server. I can think of other use cases as well.

So would Angular work is I give browser a url of a local file like C:\temp\index.html and the js files are either at c:\temp or say c:\temp\js.

So actually, I tried it, here is all in one application file (I know it should be separated)

<html ng-app="myNoteApp">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>

<div ng-controller="myNoteCtrl">

<h2>My Note</h2>

<p><textarea ng-model="message" cols="40" rows="10"></textarea></p>

<p>
<button ng-click="save()">Save</button>
<button ng-click="clear()">Clear</button>
</p>

<p>Number of characters left: <span ng-bind="left()"></span></p>

</div>

<script >
// was in separate file but pasted in for demo purposes
var app = angular.module("myNoteApp", []);

</script>
<script >
// was in separate file but pasted in for demo purposes
app.controller("myNoteCtrl", function($scope) {
    $scope.message = "";
    $scope.left  = function() {return 100 - $scope.message.length;};
    $scope.clear = function() {$scope.message = "";};
    $scope.save  = function() {alert("Note Saved:" + $scope.message);};
});
</script>
</body>
</html>

The results are, it works in Chrome and Firefox no problems, IE blocks content initially but one can allow it run.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You cannot just access an angular application by the filepath on the local machine because you will get cross origin domain errors.

The solution is to install http-server (which requires node.js to be installed). This allows you to create a http-server local to your machine and will allow you to access the Angular application as if it were hosted online for development and test purposes.

Method 2

Yes you can run a local file, but if you need data off a server, the browser should block it, depending on what version and type of browser you are running.

Here is the official Angularjs Tutorial explanation under the PhoneCat Tutorial App: Running the Development Web Server

While Angular applications are purely client-side code, and it is possible to open them in a web browser directly from the file system,
it is better to serve them from an HTTP web server. In particular, for
security reasons, most modern browsers will not allow JavaScript to
make server requests if the page is loaded directly from the file
system.

Method 3

If you need to just display data using an expression like {{mymessage}} inside a div, you don’t need a web server.

But if you need to load template html files uing ngview, you need a web server- otherwise it will complain with following error.

Request cannot load file. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

If laoding templates is needed for learning angularjs routing, I found a web server exe easy to use – HFS. So far it meets my requirements for learning AngularJS.

References

  1. HFS:Introduction
  2. HTTP File Server

Method 4

So, the way I’ve done this is to create a temp service and just load that instead of from a url/file.

Example:

//tempUser.js
angular.module("app").constant("tempUser", {
    firstname : "Joe",
    lastname : "Smith"
});

//userService.js
angular.module("app").factory("userService", function ($q, tempUser) {
    return {
        load : load
    };

    function load(id) {
        //TODO: finish impl
        return $q.when(tempUser);
    }
});

This way the controller can still work as if you were loading from a web service.

angular.module("app").controller("UserDetailCtrl", function (userService) {
    userService.load().then(function (user) {
        $scope.user = user;
    });
});

Method 5

As others have said, it’s best to serve properly as http. However, there are other workarounds.

Some editors, like Brackets (click on the lightning bolt in the top right corner while in a file), can serve the code to your browser properly. For others there might be plugins that do it.

Update: My suggestion below worked well enough for AngularJS 1, but just FYI is insufficient for Angular 2. Also see Disable same origin policy in Chrome

Further, if you’re on Chrome you can run it with flags, which means you add some stuff at behind the .exe part of the path on a short cut; options if you will. Specifically you’d want:

--allow-file-access-from-files --allow-file-access --allow-cross-origin-auth-prompt

That makes it not throw errors when trying to access files from various origins. There was a plugin for that once, but I couldn’t get it to work. Note there’s security reaosns why this isn’t the default, so maybe don’t put it on your main short cut that you use all the time for surfing… – Use at own risk.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply