Frontend employee Frontend employee - 26 days ago 13
AngularJS Question

Access-Control-Allow-Origin' issue JSON AngularJS

Just experimenting with Angular HTTP service and tried to run JSON with http service of Angular, but in the Chrome browser it would not load successfully. The console said:


XMLHttpRequest cannot load http://169.254.206.233:8081/database.json.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'null' is therefore not allowed access.


When I try to open JSON-file itself, it shows the json. But could not figure out what I do wrong.



var app = angular
.module("myModule", [])
.controller("myController", function ($scope, $http) {
$http.get("http://169.254.206.233:8081/database.json")
.success(function(response) {
$scope.smartphones = response.records;
});
});

{
"records": [
{
"name": "Mamam",
"age": 12
},
{
"name": "Jal",
"age": 18
},
{
"name": "Ziyech",
"age": 22
},
{
"name": "Dolberg",
"age": 24
}


]
}

<!doctype html>
<html lang="eng">
<head>
<title>Training</title>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

<link href="CSS/bootstrap.css" rel="stylesheet" type="text/css"/>
<link href="CSS/Styles.css" rel="stylesheet" type="text/css"/>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"" type="text/javascript"></script>
<script src="JS/angular-module.js" type="text/javascript"></script>

<body ng-app="myModule">
<div ng-controller="myController">
<ul>
<h2>Names And Age Of</h2>
<li ng-repeat="smartphone in smartphones">
{{ smartphone.name + " : " + smartphone.age }}
</li>
</ul>
</div>
</body>
</html>




Answer

it's a CORS issue.

You have to modify your backend service in order to accept CORS or in a test enviroment you can enable the Allow-Control-Allow-Origin: * extension that adds to response header rule - 'Access-Control-Allow-Origin: *'

For reference: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Comments