[英]Request available for Angular but not for web browser
I've just started learning web development. 我刚刚开始学习Web开发。 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. 我正在尝试从angular执行一个简单的http get请求以获得一个简单的json响应。 However I can manually type localhost:8080/test
and the json is rendered on my screen. 但是,我可以手动键入localhost:8080/test
,并且json会显示在屏幕上。 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. 我相信在普通应用程序中,我不应该直接看到此json。 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
在server.js
app.get('/test', function(req, res) {
res.status(200).json({'test': 'it works!'});
})
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 : 现在您已限制用户访问/ 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');
});
Now in Html like this : 现在像这样在HTML中:
<button type="button" ng-click="getData()">Get Data to user</button>
In Server.Js File 在Server.Js文件中
app.get('/test', function(req, res) {
var data = {
test : 'it works.fine !!!!'
};
res.json(data);
})
I hope you got the point.... 我希望你明白了...
Thanks & Cheers 谢谢与欢呼
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.