Julian Rubin
Julian Rubin

Reputation: 1235

Request available for Angular but not for web browser

I've just started learning web development. Sorry if there is similiar question, but I couldn't find the satisfying answer. I'm trying to perform a simple http get request from angular to obtain a simple json response. However I can manually type localhost:8080/test and the json is rendered on my screen. Is there any standard solution for getting information from server with angular? I believe in normal application I shouldn't be able to see this json directly. I have:

controllers.js

var myApp = angular.module('myApp',[]);

myApp.controller('myController', function($scope, $http) {
    $http.get('/test').success(function(data) {
        $scope.greeting = data.test;
    });        
})

in server.js

app.get('/test', function(req, res) {
    res.status(200).json({'test': 'it works!'});
})

Upvotes: 0

Views: 61

Answers (1)

Amulya Kashyap
Amulya Kashyap

Reputation: 2373

var myApp = angular.module('myApp', ['ngRoute']);

myApp.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {

    $routeProvider
        .when('/', {
            templateUrl: '/home',
            controller:'homeCtrl'
        })
        .when('/test', {
            templateUrl: '/test',
            controller:'errorCtrl'
        })
        .otherwise('/')
}]);

Now you've restricted user from visiting /test page.Then look here :

myApp.controller('homeCtrl', function ($scope) {
    $scope.getData = function(){
        $http.get('/test').then(function success(response){
           $scope.data = response.data;
         }, function error(error){
          console.log(error);
       });
    }
});

smpApp.controller(errorCtrl', function ($scope, $location) {
   $location.path('/home');
});

Now in Html like this :

<button type="button" ng-click="getData()">Get Data to user</button>

In Server.Js File

app.get('/test', function(req, res) {
   var data = {
     test : 'it works.fine !!!!'
   };
   res.json(data);
})

I hope you got the point....

Thanks & Cheers

Upvotes: 1

Related Questions