AngularJS、Node.js、ExpressJS 应用程序集成问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17451834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AngularJS , Node.js, ExpressJS application integration issue
提问by niran
I have created a RESTful service using Node.js and ExpressJS. Now I would like to implement View part. For this I have chosen AngularJS.
我使用 Node.js 和 ExpressJS 创建了一个 RESTful 服务。现在我想实现 View 部分。为此,我选择了 AngularJS。
Problem here is, I am not sure how to organize folder structure and how to integrate AngularJS with Node.js and ExpressJS.
这里的问题是,我不确定如何组织文件夹结构以及如何将 AngularJS 与 Node.js 和 ExpressJS 集成。
I watched this video, but for this no sample source code available.
我观看了这个视频,但没有可用的示例源代码。
Let's Get CRUDdy: AngularJS and Node.js Ferrari Example
让我们了解 CRUDdy:AngularJS 和 Node.js 法拉利示例
Project folder structure
项目文件夹结构


ExpressJS file
ExpressJS 文件
var express = require('express'),
http = require('http'),
path = require('path'),
photos = require('./routes/photos');
var app = express();
app.configure(function () {
app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */
app.use(express.bodyParser());
app.use(app.router);
});
app.get('/photos', photos.findAll);
app.get('/view1', photos.index);
AngularJS:
AngularJS:
// Declare app level module which depends on filters, and services
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives', 'myApp.controllers']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {templateUrl: 'partials/partial1.html', controller: 'MyCtrl1'});
$routeProvider.when('/view2', {templateUrl: 'partials/partial2.html', controller: 'MyCtrl2'});
$routeProvider.otherwise({redirectTo: '/view1'});
}]);
When I hit url http://www.domain/view1, it should display index.html. But I am getting 404 code.
当我点击 url http://www.domain/view1 时,它应该显示index.html. 但是我收到了 404 代码。
Please let me know if you need more info on it.
如果您需要更多信息,请告诉我。
回答by Will M
If you're using AngularJS to implement a single-page experience then you should serve the same front-end code every time, and then have AngularJS take over processing the URLs and displaying the content.
如果您使用 AngularJS 来实现单页体验,那么您应该每次都提供相同的前端代码,然后让 AngularJS 接管处理 URL 并显示内容。
Remember that you are managing two routing systems. One for the front-end and one for the backend. Express routes map to your data, usually returned in JSON format. (You can also render html directly, see Option #1.) Angular routes map to your templates and controllers.
请记住,您正在管理两个路由系统。一份用于前端,一份用于后端。Express 路由映射到您的数据,通常以 JSON 格式返回。(您也可以直接渲染 html,请参阅选项 #1。)Angular 路由映射到您的模板和控制器。
Option #1:
选项1:
Set static folder to serve front-end code (HTML/CSS/JS/AngularJS).
设置静态文件夹以提供前端代码(HTML/CSS/JS/AngularJS)。
app.use(express.static(__dirname + '/public'));
Look at these for sample code:
查看这些示例代码:
Directory Structure:
目录结构:
public/
index.html
js/
angular.js
css/
partials/
partial1.html
partial2.html
app/
node_modules/
routes/
web-server.js
Option #2:
选项#2:
Serve the front-end code and backend code on separate servers.
在单独的服务器上提供前端代码和后端代码。
This doesn't mean you have to have two machines.
这并不意味着您必须拥有两台机器。
Here is a workable set up on your local machinewith Apache:
这是在您的本地机器上使用Apache进行的可行设置:
Directory Structure:
目录结构:
public/
index.html
js/
angular.js
css/
partials/
partial1.html
partial2.html
node/
app/
node_modules/
routes/
web-server.js
Set up hosts file
设置主机文件
127.0.0.1 domain.dev
Set up http://domain.dev/to point to public/
设置http://domain.dev/指向 public/
<VirtualHost *:80>
DocumentRoot "/path/to/public"
ServerName domain.dev
ServerAlias www.domain.dev
</VirtualHost>
Set up http://api.domain.dev/to point to the running node web-server
设置http://api.domain.dev/指向正在运行的节点 web-server
<VirtualHost *:80>
ServerName api.domain.dev
ProxyPreserveHost on
ProxyPass / http://localhost:3000/
</VirtualHost>
(Adapted from: http://www.chrisshiplet.com/2013/how-to-use-node-js-with-apache-on-port-80/)
(改编自:http: //www.chrisshiplet.com/2013/how-to-use-node-js-with-apache-on-port-80/)
Start (or restart) Apache and run your node server:
启动(或重新启动)Apache 并运行您的节点服务器:
node web-server.js
Angular Routes:
角度路线:
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives',
'myApp.controllers'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {templateUrl: 'partials/partial1.html', controller: 'MyCtrl1'});
$routeProvider.when('/view2', {templateUrl: 'partials/partial2.html', controller: 'MyCtrl2'});
$routeProvider.otherwise({redirectTo: '/view1'});
}]);
index.html:
索引.html:
<!DOCTYPE html>
<html>
<head><title>Angular/Node exmaple</title></head>
<body>
<div id="main" ng-view></div>
</body>
</html>
Express Routes:
快速路线:
app.get('/', photos.index);
app.get('/photos', photos.findAll);
Access these routes in an Angular controller via $http or $resource service:
通过 $http 或 $resource 服务在 Angular 控制器中访问这些路由:
$http.get('http://api.domain.dev/photos').success(successCallback);
Additional Resources:
其他资源:
回答by Mister P
I had an existing angular project with a file structure like this (roughly):
我有一个现有的 angular 项目,其文件结构如下(大致):
/
app/
img/
scripts/
styles/
templates/
index.html
test/
I just created a new express app, and copied the contents of my app directory over to the /public directory in express, after removing all the existing content from /public
我刚刚创建了一个新的 express 应用程序,并在从 /public 中删除所有现有内容后,将我的应用程序目录的内容复制到 express 中的 /public 目录中
Then in the app.js file in express I did the following changes to the default config:
然后在 express 中的 app.js 文件中,我对默认配置进行了以下更改:
var express = require('express');
var routes = require('./routes');
// ** required my route module
var menu = require('./routes/menu');
var http = require('http');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
// ** I moved this above the app.router line below, so that static routes take precedence
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
// ** removed the default index route
// app.get('/', routes.index);
// ** defined my route
app.get('/api/menu', menu.list);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Then obviously wrote my route file in express and changed the URL in the angular service to use the new api.
然后显然在express中写了我的路由文件并更改了angular服务中的URL以使用新的api。
Also there was more work involved deciding where to put the specs and also merging the bower and node dependancies etc but that is probably too specific to my situation to include with this answer but happy to share if anyone might find it useful.
还有更多的工作涉及决定在哪里放置规范以及合并凉亭和节点依赖等,但这可能对我的情况太具体了,无法包含在这个答案中,但如果有人觉得它有用,我很乐意分享。

