请求新页面时如何将 AngularJS 路由与 Express (Node.js) 一起使用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13222252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:35:44  来源:igfitidea点击:

How to use AngularJS routes with Express (Node.js) when a new page is requested?

node.jsexpressangularjs

提问by winduptoy

I'm using Express, which loads AngularJS from a static directory. Normally, I will request http://localhost/, in which Express serves me my index.htmland all of the correct Angular files, etc. In my Angular app, I have these routes setup, which replace the content in an ng-view:

我正在使用 Express,它从静态目录加载 AngularJS。通常,我会请求http://localhost/, Express 在其中为我提供我index.html和所有正确的 Angular 文件等。在我的 Angular 应用程序中,我设置了这些路由,它们替换了 中的内容ng-view

$routeProvider.when('/', {
    templateUrl: '/partials/main.html',
    controller: MainCtrl,
});

$routeProvider.when('/project/:projectId', {
    templateUrl: '/partials/project.html',
    controller: ProjectCtrl,
});

$locationProvider.html5Mode(true);

On my main page, I have a link to <a href="/project/{{project.id}}">, which will successfully load the template and direct me to http://localhost/project/3or whatever ID I have specified. The problem is when I try to direct my browser to http://localhost/project/3or refresh the page, the request is going to the Express/Node server, which returns Cannot GET /project/3.

在我的主页上,我有一个指向 的链接<a href="/project/{{project.id}}">,它将成功加载模板并将我定向到http://localhost/project/3或我指定的任何 ID。问题是当我尝试将浏览器定向到http://localhost/project/3或刷新页面时,请求将发送到 Express/Node 服务器,该服务器返回Cannot GET /project/3.

How do I setup my Express routes to accommodate for this? I'm guessing it will require the use of $locationin Angular (although I'd prefer to avoid the ugly ?searches and #hashes they use), but I'm clueless about how to go about setting up the Express routes to handle this.

我如何设置我的 Express 路线以适应这种情况?我猜它需要$location在 Angular 中使用(尽管我更愿意避免使用丑陋的 ?searches 和 #hashes),但我对如何设置 Express 路由来处理这个问题一无所知。

Thanks.

谢谢。

采纳答案by Michelle Tilley

I would create a catch-all handler that runs afteryour regular routes that sends the necessary data.

我会创建一个包罗万象的处理程序,它发送必要数据的常规路由之后运行。

app = express();
// your normal configuration like `app.use(express.bodyParser());` here
// ...
app.use(app.router);
app.use(function(req, res) {
  // Use res.sendfile, as it streams instead of reading the file into memory.
  res.sendfile(__dirname + '/public/index.html');
});

app.routeris the middleware that runs all of your Express routes (like app.getand app.post); normally, Express puts this at the very end of the middleware chain automatically, but you can also add it to the chain explicitly, like we did here.

app.router是运行所有 Express 路由(如app.getapp.post)的中间件;通常,Express 会自动将其放在中间件链的最末端,但您也可以像我们在这里所做的那样将其显式添加到链中。

Then, if the URL isn't handled by app.router, the last middleware will send the Angular HTML view down to the client. This will happen for anyURL that isn't handled by the other middleware, so your Angular app will have to handle invalid routes correctly.

然后,如果 URL 未由 处理app.router,则最后一个中间件会将 Angular HTML 视图向下发送到客户端。对于其他中间件未处理的任何URL,都会发生这种情况,因此您的 Angular 应用程序必须正确处理无效路由。

回答by Guillaume Vincent

with express 4, you probably want to catch all requests and redirect to angularjs index.htmlpage. app.use(app.router);doesn't exist anymore and res.sendfileis deprecated, use res.sendFilewith an uppercase F.

使用 express 4,您可能想要捕获所有请求并重定向到 angularjsindex.html页面。 app.use(app.router);不再存在且res.sendfile已弃用,请res.sendFile与大写F 一起使用

app.post('/projects/', projectController.createProject);
app.get('/projects/:id', projectController.getProject);
app.get('*', function (req, res) {
    res.sendFile('/public/index.html');
});

put all your API routes before the route for every path app.get('*', function (req, res){...})

将所有 API 路由放在每条路径的路由之前app.get('*', function (req, res){...}

回答by winduptoy

I guess I should have clarified that I wasn't interested in using a template engine, but having Angular pull all of the HTML partials on it's own, Node is functioning completely as a static server here (but it won't be for the JSON API. Brian Ford shows how to do it using Jade here: http://briantford.com/blog/angular-express.html

我想我应该澄清一下,我对使用模板引擎不感兴趣,但是让 Angular 自行提取所有 HTML 部分,Node 在这里完全作为静态服务器运行(但它不会用于 JSON API。Brian Ford 在此处展示了如何使用 Jade 进行操作:http: //briantford.com/blog/angular-express.html

My app is a single-page app, so I created an Express route for each possible URL pattern, and each of them does the same thing.

我的应用程序是一个单页应用程序,所以我为每个可能的 URL 模式创建了一个 Express 路由,并且它们中的每一个都做同样的事情。

fs.readFile(__dirname + '/public/index.html', 'utf8', function(err, content) {
    res.send(content);
});

I was assuming I would have to pass some request variables to Angular, but it looks like Angular takes care of it automatically.

我假设我必须将一些请求变量传递给 Angular,但看起来 Angular 会自动处理它。