AngularJS和Express路由问题 [英] AngularJS and Express Routing issue
问题描述
我使用AngularJS和ExpressJS并且有路由问题。我看到很多其他的帖子,但是这些解决方案似乎都没有。这是我在Express的路线:
module.exports = function(app,auth){
// Api routes
var mycontroller = require('../ app / controllers / mycontroller');
app.get('/ api / dostuff /:id',mycontroller.getBlockByHash);
// Home route
app.get(/,function(req,res){
res.render('index');
}) ;
};
当我去我的根 /
一切都按预期工作。 ExpressJS服务我的索引,角度取其他的。当我点击链接 / blocks
,它的工作原理是因为AngularJS拾取路由。但是当我刷新时,我发现404找不到错误。
我尝试过 app.get('*'
相反,这给我一个完全不同的错误,没有加载。
我正在使用 Jade
创建基本的页面结构, 。我的Express配置是:
app.use(express.favicon());
app.use(express .static(config.root +'/ public'));
使用html5Mode时,文档说:
使用此模式需要在服务器端进行URL重写,基本上您必须将所有链接重写到应用程序的入口点(例如index.html)
没有提到的是:
- 您应该排除静态资源,如脚本/样式/图像/字体等。
- 您还应该排除您的 Restful API 。
您的案例:
使用 express .static
提供静态资产,然后使用 app.get('*',
将所有其他请求重定向到您的angular.js入口点index.html)。
express.js中间件订单执行计数!
-
express.static
必须在app.router
- Node.js / Express.js - app.router如何工作? a>
I'm using AngularJS and ExpressJS and having an issue with routing. I saw many other posts but none of those solutions seemed to work. Here is my routes in Express:
module.exports = function(app, auth) {
//Api routes
var mycontroller = require('../app/controllers/mycontroller');
app.get('/api/dostuff/:id', mycontroller.getBlockByHash);
//Home route
app.get("/", function(req, res) {
res.render('index');
});
};
When I go to my root /
, everything works as expected. ExpressJS serves up my index and angular picks up the rest. When I click a link /blocks
, it works as expected since AngularJS picks up the route. But when I refresh, I get a 404 not found error.
I tried app.get('*'
instead, but that gives me a completely different error where nothing loads.
I'm using Jade
to create the basic page structure with Express. My Express config is:
app.use(express.favicon());
app.use(express.static(config.root + '/public'));
When using html5Mode the documentation says:
Using this mode requires URL rewriting on server side, basically you have to rewrite all your links to entry point of your application (e.g. index.html)
What it doesn't mention is:
- You should exclude static assets like scripts/styles/images/fonts etc.
- You should also exclude your Restful API.
Your case:
The error you got there is express serving html into script tags and the browser fails to parse them as a valid javascript.
Use express.static
to serve static assets and then use app.get('*',
for redirecting all other requests to your angular.js entry point (index.html).
express.js middleware order do counts!
express.static
must be declared beforeapp.router
- Node.js / Express.js - How does app.router work?
这篇关于AngularJS和Express路由问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!