如何 运行 NodeJS API 与 Angular app.js 文件?

How to run NodeJS API with Angular app.js file?

我正在按照我在网上找到的一些教程创建一个使用 RESTful API 和 MEAN 堆栈的 Web 应用程序。

我在同时实施 API 服务器和 Angular 路由时遇到问题。我已经创建了一个 server.js 文件来处理到 /api/ 的路由,所以例如我有:

...
app.get('/api', function(req, res) {
    res.status(200).json({"message": "Welcome to the app"});
});

因此,当 API 服务器收到请求时,它只会发回一条 JSON 消息。现在我还有一个 public 文件夹,里面有一个 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;
    });
});

因此,当我从命令行 运行ning node server.js 启动我的服务器并转到 localhost:5000(或任何端口)时,我得到一个 Cannot GET /

我假设这是因为我的 server.js 文件中没有到 '/' 的路由。

我如何 运行 应用程序先从 app.js 文件中移除并让它使用 API?

您无法获取 /,因为该应用尚未安装到您的服务器上。为此,您需要创建一个入口点,该入口点将成为来自服务器的服务器,而服务器又将处理您的所有 angular 路由、视图、控制器等
在您的 server.js 文件中,对于与您定义的任何 api 路由不匹配的每个请求,您需要将其转发到您的 angular 应用程序,其中 ng-route 将加载与您请求的 URL 相对应的视图。
安装:

app.get('*', function(request, response){
  response.sendfile('/path/to/your/entry.html');
});

现在这个 entry.html 将包含您的 angular 应用程序(或您为此使用的任何前端框架)

您不需要为 index.html 文件创建路由,只需将以下行添加到服务器文件并将 index.html 文件放入客户端文件夹即可。

app.use(express.static(path.join(__dirname, '<client_folder_name>')));

当您启动服务器并打开 http://localhost:5000 时,index.html 文件会自动呈现。

您可以通过以下 4 个步骤完成:

1- 创建您的 index.html 文件并将 api 放在那里:

app.get('/api', function(req, res) {
    res.status(200).json({"message": "Welcome to the app"});
});

2- 需要在 server.js 中新建 index.html 文件:

var routes = require('./index');

3- 创建服务器并监听一个端口:

var server = app.listen(5000, function () {
    console.log('nodejs server is listening on port 5000!');
});

4- 在 server.js 中使用 index.html 文件:

app.use('/',routes);