我正在關注一些我在網上找到的用於創建使用RESTful API和MEAN堆棧的Web應用程序的教程。如何使用Angular app.js文件運行NodeJS API?
我無法一起實現API服務器和Angular路由。我創建了一個server.js
文件處理路線/api/
,所以,比如我有:
...
app.get('/api', function(req, res) {
res.status(200).json({"message": "Welcome to the app"});
});
所以當API服務器收到一個請求,它只是發回一個JSON消息。現在,我也有一個app.js
文件中有對角碼公用文件夾:
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的入口點運行的應用程序。你使用快遞嗎? – Zeokav
是的,我使用快遞。我在server.js文件中定義了所有的API路由。我只是不確定如何將它連接到有角度的一面 –