node.js 使 Angular 路由与 Express 路由一起使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30546524/
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 18:48:48  来源:igfitidea点击:

Making Angular routes work with Express routes

angularjsnode.jsexpress

提问by kirgol

I've got in impasse with setting Angular routes to work with Express.

我在设置 Angular 路由以使用 Express 时陷入僵局。

I tried to do like here Express 4, NodeJS, AngularJS routingbut that did not work. The static index.html serves each time the url changes, but the Angular does not catch the partial.

我试图在这里做Express 4、NodeJS、AngularJS 路由,但没有奏效。每次 url 更改时,静态 index.html 都会提供服务,但 Angular 不会捕获部分。

In my Express I have the following code:

在我的 Express 中,我有以下代码:

var express = require("express");
var app = express();
app.use(express.static(__dirname + '/app'));
app.use("*",function(req,res){
    res.sendFile(path.join(__dirname,"app/index.html"));
});
app.listen(1337, function(){
    console.log("Server is listening on port 1337");
});

And in my Angular app, I have the following:

在我的 Angular 应用程序中,我有以下内容:

var app = angular.module("myapp",["ngRoute","appControllers"]);

    app.config(["$routeProvider","$locationProvider",function($routeProvider,$locationProvider){
            $locationProvider.html5Mode(true);
            $routeProvider
                    .when("/list",{
                        templateUrl: "/partials/users.html",
                        controller: "userListCntr"
            })
                    .when("/edit", {
                        templateUrl: "/partials/edit.html",
                        controller: "userEditCntr"
            })
                    .when("/register", {
                        templateUrl: "/partials/register.html",
                        controller: "registerCntr"
            })
                    .when("/login", {
                        templateUrl: "/partials/login.html",
                        controller: "registerCntr"
            });

    }]);

I don't have any errors in my browser console. The html inspector shows: <!-- ngView: -->so the directive is kind of initialized.

我的浏览器控制台中没有任何错误。html 检查器显示: <!-- ngView: -->所以指令有点初始化。

And dependency list:

和依赖列表:

dependencies": {
    "angular": "1.3.x",
    "angular-mocks": "1.3.x",
    "jquery": "1.10.2",
    "bootstrap": "~3.1.1",
    "angular-route": "1.3.x",
    "angular-resource": "1.3.x",
    "angular-animate": "1.3.x"
  }

here is my file structure:

这是我的文件结构:

--app (angular app)
   --components
   --js
   --css
   --img
   --assets
   --partials
   --index.html
--node-modules
--server.js (here express settigs are)

ALso, I made changes as follows to account for all static resources, but still does not work:

另外,我对所有静态资源进行了如下更改,但仍然不起作用:

app.use(express.static(__dirname+ "/app"));
app.use('/js', express.static(__dirname + '/app/js'));
app.use('/dist', express.static(__dirname + '/../dist'));
app.use('/css', express.static(__dirname + '/app/css'));
app.use('/assets', express.static(__dirname + '/app/assets'));
app.use('/components', express.static(__dirname + '/app/components'));
app.use('/img', express.static(__dirname + '/app/img'));
app.use('/partials', express.static(__dirname + '/app/partials'));

app.all('/*', function(req, res, next) {
    // Just send the index.html for other files to support HTML5Mode
    res.sendFile('/app/index.html', { root: __dirname });
});

Please, help, because I can't find a solution. Thanks!

请帮助,因为我找不到解决方案。谢谢!

回答by joshuahiggins

When you don't pass a path to express.use(), then it defaults to /. The proceeding rule you set for *is either redundant or may not even work.

如果您不将路径传递给express.use(),则它默认为/。您设置的处理规则*要么是多余的,要么甚至可能不起作用。

Also, since you're using html5mode, you need to explicitly set apart routes from resources so Express doesn't try to serve up your index.htmlfile for all requests.

此外,由于您正在使用html5mode,您需要明确地将路由与资源分开,以便 Express 不会尝试index.html为所有请求提供您的文件。

Try this example from Angular UI-Routeron for size:

Angular UI-Router试试这个例子的大小:

var express = require('express');
var app = express();

app.use('/js', express.static(__dirname + '/js'));
app.use('/dist', express.static(__dirname + '/../dist'));
app.use('/css', express.static(__dirname + '/css'));
app.use('/partials', express.static(__dirname + '/partials'));

app.all('/*', function(req, res, next) {
    // Just send the index.html for other files to support HTML5Mode
    res.sendFile('index.html', { root: __dirname });
});

app.listen(3006); //the port you want to use

回答by kirgol

Thanks everybody for help. I resolved the question by inserting <base href="/" />into head section of my Angular index.html. It worked for me, but as of now it's like magic and cargo coding, since I don't understand why it works :) Found solution here: AngularJS: how to enable $locationProvider.html5Mode with deeplinking

谢谢大家的帮助。我通过插入<base href="/" />Angular index.html 的 head 部分解决了这个问题。它对我有用,但截至目前它就像魔术和货物编码,因为我不明白它为什么起作用:) 在这里找到解决方案:AngularJS:如何使用深层链接启用 $locationProvider.html5Mode

回答by Carlos Muentes

I just want to add that adding base href=helped me. I have my app statically served in express and browsing directly to routes in my angular app would cause lots of

我只想补充一点,添加base href=对我有帮助。我在 express 中静态地提供了我的应用程序,并且直接浏览到我的 angular 应用程序中的路由会导致很多

refused to execute script because its mime type ('text/html') is not executable and strict mime type checking is enabled

拒绝执行脚本,因为它的 MIME 类型 ('text/html') 不可执行并且启用了严格的 MIME 类型检查

errors to be throw. But adding base hreffixed that and I can browse directly to my angular routes now.

要抛出的错误。但是添加base href固定的,我现在可以直接浏览到我的角度路线。

回答by rahulthakur319

While the solution suggested by @kirgol of using base href=works fine, there is an alternative solution which might interest someone looking for simple route serve. In this solution we will not using ExpressJS routing

虽然@kirgol 建议的使用解决方案base href=工作正常,但有一个替代解决方案可能会让寻找简单路由服务的人感兴趣。在这个解决方案中,我们不会使用 ExpressJS 路由

Simply use this

简单地使用这个

app.use(express.static(__dirname + '/app'));

instead of this

而不是这个

app.all('/*', function(req, res, next) {
    // Just send the index.html for other files to support HTML5Mode
    res.sendFile('index.html', { root: __dirname });
});

This way expressJS will automatically serve the index.html present at that static location & will handle the routing automatically. It will behave just like a simple http server. The moment you handle the routing using app.all/ app.get- you will have to set base hrefto tell $locationProviderof location from which it can match routes

这样 expressJS 将自动为该静态位置的 index.html 提供服务并自动处理路由。它的行为就像一个简单的 http 服务器。使用app.all/ 处理路由的那一刻app.get- 您必须设置base href告诉$locationProvider它可以匹配路由的位置