Search code examples
javascriptangularjsjsonxmlhttprequestlocal

Load local json file


I want to create a simple local website to visualize my json data that is generated from my protractor tests. The problem is angular doesn't support loading local files, so do you know if there is any way I can use this JSON locally? I don't want to setup a server just to load a single small file to a single variable.

I tried $http, but that obviously throws XMLHttpRequest Cross origin request. I appreciate any suggestion.

EDIT: I decided to run http-server from npm. I start it on port 8080 and specify path to my project. Then I have

var app = angular.module("reportingApp", ['nvd3']);

app.controller('MainController', ['$scope', '$rootScope', '$http', function($scope, $rootScope, $http) {
    $scope.title = 'abc';

    $http.get('http://127.0.0.1:8080/e2e-Report/combined.json').success(function(data) {
        $scope.title = data.jsonData;
        });
}]);

in my app.js to get the file via http, but it throws No 'Access-Control-Allow-Origin' header is present on the requested resource


Solution

  • You can create Local server by installing
    npm install http-server -g

    Once it is installed, go to command line ->Path to your project ->http-server &

    Ex.

    D:\angularProject> http-server & (Press Enter)
    

    It will start localhost server: localhost://8080. Open localhost://8080 on your browser.

    Now,your CORS issue will not there. Enjoy.

    EDIT: You need node to be installed in your machine.

    Sample code:

    $http.get("api/my.json").then(function (res){
                console.log("res",res);
    
            })