Angular 和 Express 路由 [英] Angular and Express routing
问题描述
我经历了许多 Angular-express 种子,并了解了它们的工作原理.我遇到的问题是:1). 我想使用 ejs-locals 进行模板化.2). 如何正确配置服务器端和客户端的路由.而且,在输入诸如 /about
之类的 URL 时,不要生成错误:cannot/get
I've been through many Angular-express seeds and kind of worked out how they work.
The problem I am having is: 1). I would like to use ejs-locals for templating. 2). How to configure correctly the routing of the server-side and client-side. And also, when entering a URL such as /about
, not to generate the error: cannot /get
angular app.js 包含:
angular app.js contains:
// angular stuff
$routeprovider.when('/', {
templateUrl: 'index',
controller: IndexCtrl
});
$routeprovider.when('/about', {
templateUrl: 'partials/about',
controller: IndexCtrl
});
express app,js 包含:
app.get('/', routes.index);
app.get('/about', routes.about);
routes 文件夹 包含index.js":
routes folder contains 'index.js':
exports.index = function(req, res){
res.render('index',{name:"Hello"});
};
exports.about = function (req, res) {
res.render('partials/about');
};
Views 文件夹 包含 index.ejs
:
<!--HTML head/navigation bar here-->
<div ng-view></div>
在 views 文件夹中是一个 partials
文件夹:(观看次数/部分/)
and inside views folder is a partials
folder:
(Views/partials/)
index.ejs:
<h1>Index</h1>
about.ejs:
<h1>About</h1>
推荐答案
将这些路由添加到您的 express 服务器
Add these routes to your express server
app.get('/partials/:filename', routes.partials);
app.use(routes.index);
然后在 routes.js
exports.partials = function(req, res){
var filename = req.params.filename;
if(!filename) return; // might want to change this
res.render("partials/" + filename );
};
exports.index = function(req, res){
res.render('index', {message:"Hello!!!"});
};
这将确保 express 在向 partials/index
和 partials/about
发出请求时返回呈现的模板.
This will make sure that express returns rendered templates when making requests to partials/index
and partials/about
.
这是一个要点:https://gist.github.com/4277025
这篇关于Angular 和 Express 路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!