使用AngularJS在node.js中查看模板和路由(View templates and routes in node.js with AngularJS)

编程入门 行业动态 更新时间:2024-10-28 15:25:26
使用AngularJS在node.js中查看模板和路由(View templates and routes in node.js with AngularJS)

试图了解如何在node.js express app中实现AngularJS。 设置快递后,我需要两件事:路由和模板引擎,所以通常我需要按照以下步骤设置应用程序以使用Jade模板引擎:

app.register('.html', require('jade'));

...然后我会设置这样的路线:

app.get('/', function(req, res) { res.render('index', function(err, html){ // ... }); });

但如果我想使用AngularJS进行模板化,我还需要Jade吗? 我读到了AngularJS路由必须如何配置,这是否意味着使用AngularJS时不再需要使用app.get()声明路由的上述方法?

Trying to understand how to implement AngularJS in a node.js express app. After setting up express, I need 2 things: routing and a template engine, so normally I would need to do as follows to set the app to use Jade templating engine:

app.register('.html', require('jade'));

...and then I would set routes probably like this:

app.get('/', function(req, res) { res.render('index', function(err, html){ // ... }); });

But if I want to use AngularJS for templating, do I still need Jade? And I read about how in AngularJS routes must be configured, does this mean the above way of declaring routes with app.get() would no longer be needed when using AngularJS?

最满意答案

如果在渲染客户端页面之前不需要为Angular布局添加任何额外内容(即在某些情况下,您可以在使用PassportJS时在Jade模板中添加window.user对象进行身份验证),则可以完全丢弃Jade一起让Express静态中间件呈现你的index.html :

app.use(express.static(path.join(__dirname, 'public')));

显然, public/中的文件都是你的Angular文件,包括index.html 。 确保path模块也需要路径规范化,但这不是必需的。

之后,Angular将负责其余的工作。 这意味着您的所有路线都在Angular应用内定义,而不是在Express路线中定义。

If you don't need to add anything extra to your Angular layout prior to rendering the page for the client (i.e. in some cases you could add a window.user object in the Jade template for authentication when using PassportJS), you can completely ditch Jade altogether and let the Express static middleware render your index.html:

app.use(express.static(path.join(__dirname, 'public')));

Obviously, the files in public/ are all your Angular files, including the index.html. Be sure to require the path module too for path normalization, this isn't required though.

Afterwards, Angular will take care of the rest. This means that all your routes are defined inside the Angular app, and not in the Express routes.

更多推荐

本文发布于:2023-07-20 12:33:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1199606.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路由   模板   js   AngularJS   node

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!