【问题标题】:Request available for Angular but not for web browser请求可用于 Angular 但不适用于 Web 浏览器
【发布时间】:2016-03-10 10:13:53
【问题描述】:

我刚刚开始学习网络开发。抱歉,如果有类似的问题,但我找不到令人满意的答案。我正在尝试从 angular 执行一个简单的 http get 请求,以获得一个简单的 json 响应。但是我可以手动输入localhost:8080/test,然后 json 就会呈现在我的屏幕上。有没有任何标准的解决方案可以从有角度的服务器获取信息?我相信在正常的应用程序中我不应该直接看到这个 json。我有:

controllers.js

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

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

server.js

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

【问题讨论】:

  • 好吧,代码有效。我问如何让 Angular 从服务器获取一些东西,但不要让用户通过输入正确的 url 来获取原始 json。
  • 但是您的问题仍然不是很清楚,但根据我的说法,您可以通过在其上放置任何锚标记来做到这一点,以便每当任何用户点击时。您将在屏幕上获得数据。以 json 格式向用户显示数据并不是最佳实践。因此将其转换为数组/字符串,然后在 html/jade/ejs 上显示您正在使用的任何内容。
  • 据我所知,有角度的网站是轻量级的,因为服务器不必将整个页面作为请求传递。假设服务器返回页面,然后用户单击某个按钮,客户端需要来自服务器的一些信息。所以我读过服务器应该用json回答角度。然后角度可以更新数据。在我的控制器中,这是$scope.greeting = data.test。但是使用我当前的解决方案,用户只需输入 url bar server_adress/test,他也会得到 json。我不希望这种情况发生。我希望我的服务器在 /test 只在 Angular 调用它时回答它。
  • 哦,.....现在我很清楚你的问题了。因此,您应该限制用户在控制器的路由配置中访问 server_path/test。当您希望显示数据时,只需发送这样的 XHR 请求 $http.get('/test').then().... 就完成了.. 希望这次能有所帮助
  • 你明白了。我仍然不知道如何一方面在路由配置中限制用户,另一方面在 XHR 到达时传递 json。你能发布任何sn-p吗?

标签: angularjs json http express


【解决方案1】:
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('/')
}]);

现在您已限制用户访问 /test 页面。那么请看这里:

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');
});

现在在 Html 中是这样的:

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

在 Server.Js 文件中

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

我希望你明白了......

感谢和欢呼

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-25
    • 2021-03-31
    • 2021-05-24
    • 2014-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多