【问题标题】:Angularjs route for node express js backendnode express js后端的Angularjs路由
【发布时间】:2016-06-27 08:26:17
【问题描述】:

我创建了一个带有 Angular js 前端的 nodejs 后端。我有以下用于路由的 angularjs 代码。

var myApp = angular.module('myApp ', ['ngRoute']);

myApp .config(['$routeProvider', '$locationProvider', function($routeProvider){
    $routeProvider
        .when('/login', {
            templateUrl : 'login.html',
            controller: 'loginController'
        }).otherwise({
            templateUrl : 'main.html',
            controller  : 'mainController'
        });
}]);

我的 app.js 包含以下代码。 (注:我使用的是express js框架3.0)

app.use(app.router);
app.use('/',function(req, res) {
    res.sendfile(__dirname + '/public/index.html');
});

我把所有的html都放在public文件夹里,结构是这样的。

    public/
            -css folder
            -angular dependencies
            -all my htmls (index.html,login.html,main.html)
    routes/
            -index.js
    views/
            -index.ejs
            -error.ejs
    app.js

现在,当我点击我的基本网址时,index.html 会根据我在上面给出的 app.js 中提供的代码加载。然后角度在 ng-view div 中插入 main.html 代码。当我点击 /login 时,我希望加载 login.html。但相反,正在加载相同的 main.html。有人可以对此有所了解吗?解决方案很少,但没有一个能帮到我。

【问题讨论】:

    标签: javascript angularjs node.js angularjs-routing


    【解决方案1】:

    我认为你想要类似于express.static 的东西

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

    如果收到“login.html”请求,它将首先检查该文件的公共目录。

    【讨论】:

    • 我的申请中确实有这个。
    【解决方案2】:

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

    这对我有帮助。

    我做了修改

    myApp.config(['$routeProvider', '$locationProvider',
        function($routeProvider,$locationProvider){
            $routeProvider
            .when('/login', {
                templateUrl : 'login.html',
                controller: 'loginController'
            }).when('/', {
                templateUrl : 'main.html',
                controller  : 'mainController'
            });
        $locationProvider.html5Mode(true);
    }]);
    

    对 app.js 的更改

    app.use(express.static(path.join(__dirname, 'public')));
    app.use(express.static(__dirname + '/public'));
    app.use(app.router);
    app.use('/',function(req, res) {
      res.sendfile(__dirname + '/public/index.html');
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-26
      • 1970-01-01
      • 2013-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-07
      • 1970-01-01
      相关资源
      最近更新 更多