我在带有 ExpressJS 的 NodeJS 服务器上有一个 AngularJS 应用程序。现在我将 Angular 应用程序作为静态文件提供:
app.use(express.static(__dirname + '/app'));
但是在导航中,我有一个 # 符号:
http://127.0.0.1:8080/#/queryes
为了解决这个问题,我把这段代码放在了 Angular Router 中:
$locationProvider.html5Mode(true);
但是现在我无法获得部分 View 。如何将 Angular Routes 与 ExpressJS 混合使用?
最佳答案
为了将 AngularJS html5mode 与 Express 一起使用,您必须为所有请求提供“index.html”以将所有路由留给 AngularJS。不久前我遇到了同样的问题。
因此,首先,您声明所有 API 端点路由、任何静态文件目录(CSS、JS、partials 等),然后为所有剩余请求提供 index.html。例如:
// serve all asset files from necessary directories
app.use("/js", express.static(__dirname + "/app/js"));
app.use("/img", express.static(__dirname + "/app/img"));
app.use("/css", express.static(__dirname + "/app/css"));
app.use("/partials", express.static(__dirname + "/app/partials"));
app.use("/templates", express.static(__dirname + "/app/templates"));
// any API endpoints
app.post('/api/v1/auth/login', routes.auth.login);
// serve index.html for all remaining routes, in order to leave routing up to angular
app.all("/*", function(req, res, next) {
res.sendfile("index.html", { root: __dirname + "/app" });
});
关于ExpressJS 中的 AngularJS 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20396900/