我正在使用Node,Express和Angular开发单页应用。我的目录结构与通常的Express应用程序一样
<app>
+--public
+--routes
+--views
+--partials
|--<html files for ng view>
|--index.html
|--server.js
|--package.json
这是我的package.json
{
"name" : "app-name",
"version" : "0.0.1",
"dependencies" : {
"body-parser" : "1.9.2",
"express" : "4.10.0",
"method-override": "2.3.1"
}
}
我正在使用AngularJS进行客户端路由
// public/js/app.js
var app = angular.module('mainApp', ['ngRoute']);
app.config = (['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider
.when('/', { templateUrl: 'partials/home.html', controller: 'MainCtrl' })
.when('/about', { templateUrl: 'partials/about.html', controller: 'AboutCtrl' })
.when('/services', { templateUrl: 'partials/services.html', controller: 'ServicesCtrl' })
.otherwise({ redirectTo: '/' })
}]);
app.controller('MainCtrl', function($scope) {
$scope.message = 'I\'m the Portal';
});
app.controller('AboutCtrl', function($scope) {
$scope.message = 'Wanna know more \'bout me?';
});
app.controller('ServicesCtrl', function($scope) {
$scope.message = 'Still gonna serve ya\'!';
});
这是我的server.js:
// server.js
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.use('/views', express.static(__dirname + '/views'));
app.get('/partials/:name', function(req, res, next) {
var name = req.params.name;
res.sendFile('views/partials/' + name, { root: __dirname});
// also tried res.render, what's the difference?
});
app.get('*', function(req, res, next) {
res.sendFile('index.html', { root: __dirname + '/views' });
});
app.listen(3000, function() {
console.log("Express server listening on port %d in %s mode",
this.address().port, app.settings.env);
});
我还没有将Angular控制器和Express路由分成模块。这是我的index.html文件:
<body ng-app="mainApp">
<div class="container">
<!--
<div ng-include="'views/header.html'"></div>
REPLACED BELOW WITH THE CODE ABOVE, AND IT'S WORKING
-->
<div class="masthead">
<h3 class="text-muted"> COMPANY </h3>
<nav class="nav navbar-default">
<ul class="nav nav-justified">
<li class="active"><a href="/"> HOME </a></li>
<li><a href="/about"> ABOUT </a></li>
<li><a href="/services"> SERVICES </a></li>
</ul>
</nav>
</div>
<!-- THIS PART WON'T WORK, IN COMMENT WHEN INSPECTED -->
<div ng-view></div>
</div>
<script...></script>
</body>
我使用nodemon
启动了我的应用。我的问题是我似乎无法看到ng-view部分,但模板(ng-include
)正在运行。 ng-view
在检查时发表评论。我已经尝试在SO中寻找其他类似的问题,但他们的解决方案在我的案例中不起作用。你能指出我的代码有什么问题吗?
是否有必要使用像Jade(Pug now)或EJS这样的模板引擎来ng-view
工作?我更喜欢使用纯HTML而不是学习模板引擎。
res.sendFile
和res.render
的区别是什么? res.render
仅用于模板引擎吗?
我该如何测试呢?我怎么知道Express是否正确发送部分内容?
答案 0 :(得分:0)
尝试并更改此
app.get('*', function(req, res, next) {
res.sendFile('index.html', { root: __dirname + '/views' });
});
到此
app.get('*', function(req, res, next) {
res.sendFile('index.html');
});