【发布时间】:2017-05-15 09:22:54
【问题描述】:
我正在学习一些我在网上找到的教程,用于创建一个使用带有 MEAN 堆栈的 RESTful API 的 Web 应用程序。
我无法同时实现 API 服务器和 Angular 路由。我创建了一个server.js 文件来处理到/api/ 的路由,例如我有:
...
app.get('/api', function(req, res) {
res.status(200).json({"message": "Welcome to the app"});
});
因此,当 API 服务器收到请求时,它只会发回一条 JSON 消息。现在我还有一个公用文件夹,其中包含一个 app.js 文件,其中包含 Angular 代码:
var app = angular.module('app', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/index.html',
controller: 'AppController',
resolve: {
message: function(Message) {
return Message.getMessage();
}
}
})
.service("Message", function($http) {
this.getMessage = function() {
return $http.get('/api')
.then(function(response) {
return response;
}, function(response) {
alert("Error retrieving message");
});
}
})
.controller("AppController", function(message, $scope) {
$scope.message = message.data;
});
});
所以当我从运行node server.js 的命令行启动我的服务器并转到localhost:5000(或任何端口)时,我得到一个Cannot GET /
我假设这是因为我的server.js 文件中没有到'/' 的路由。
如何先从 app.js 文件运行应用程序并让它使用 API?
【问题讨论】:
-
您的 server.js 中需要一个入口点来运行应用程序。你用的是快递吗?
-
是的,我正在使用快递。我在 server.js 文件中定义了所有 API 路由。我只是不确定如何将它连接到有角度的一面
标签: javascript angularjs node.js rest mean-stack