AngularJS - 在url中传递参数时无法实例化模块

时间:2014-09-30 00:12:11

标签: angularjs url express url-parameters

我在routes.js文件中定义了以下网址:

app.get('/animal/:id', function(req, res, next) {
    res.sendfile('./public/views/animal.html')
});

这是app.js

var app = angular.module('adote', ['ngCookies', 'ngResource', 'ngRoute', 'ngAnimate', 'flow', 'ngTagsInput', 'ngSanitize', 'mgcrea.ngStrap'])

  app.config(function($locationProvider, $routeProvider, $httpProvider) {
        $httpProvider.defaults.useXDomain = true;
        delete $httpProvider.defaults.headers.common['X-Requested-With'];
    })

这是index.html的链接(此处不多):https://gist.github.com/larissaleite/6280ca1bcd9886e7b253

这是我在我的应用程序上进行所有配置的地方:

app.use(cookieParser('appsecret'));

app.use(session({ secret: 'appsecret', saveUninitialized: true, cookie: { secure: true, maxAge: new Date(Date.now() + 3600000) } }));

// configuration ===============================================================
var db = mongoose.connect('mongodb://127.0.0.1:27017/Routing');

// connect to mongoDB database
mongoose.connection.once('connected', function(error){
    if (error) {
        console.log("Error: " + error);
    } else {
        console.log("Connected to the database");
    }
});

app.use(express.static(__dirname + '/public'));         // set the static files location /public/img will be /img for users
app.use(bodyParser.urlencoded({extended:true}));

app.use(bodyParser.json());

app.use(passport.initialize());
app.use(passport.session());
app.use(flash());

require('./app/routes.js')(app, passport);

这是routes.js完成:

var Animal = require('./models/animal');
var User = require('./models/user');

module.exports = function(app, passport) {

    require('../config/passport')(passport); // pass passport for configuration

    app.get('/home', function(req, res, next) {
        console.log(req.isAuthenticated());
        res.sendfile('./public/views/home.html');
    });

    app.get('/cadastro', function(req, res, next) {
        res.sendfile('./public/views/cadastro.html');
    });

    app.get('/animal/:id', function(req, res, next) {
        res.sendfile('./public/views/animal.html')
    });

    app.get('/api/animals', function(req, res, next) {
        console.log("GET - api/animals");

        Animal.find({}, function(err, animals) {
            if (err) {
                console.log("erro");
                res.send(err);
            }
            if (!animals.length) {
                res.send("not found");
            } else {
                res.json(animals);
            }
        });
    });

    app.get('/api/animal/:id', function(req, res, next) {
        //changed from query to params after removing angularjs routing
        console.log("GET - api/animal/id = "+req.params.id);

        Animal.findById(req.params.id, function(err, animal) {
            if (err) {
                console.log("erro");
                res.send(err);
            } else {
                res.json(animal);
            }
        });
    });

    app.post('/api/animal', function(req, res, next) {
        console.log("POST - api/animal");

        console.log(req.body.tags);
        //console.log(req.body.localizacoes);

        var animal = new Animal({
            nome: req.body.nome,
            tipo: req.body.tipo,
            tags: req.body.tags,
            localizacoes: req.body.localizacoes,
            descricao: req.body.descricao,
            usuario_nome: "Maria Joaquina",
            eventos: req.body.eventos
        });

        animal.save(function(err) {
            if (err)
                res.send(err);

            res.send("success");
        }); 
    });

    // =====================================
    // FACEBOOK ROUTES =====================
    // =====================================
    // route for facebook authentication and login
    app.get('/auth/facebook', passport.authenticate('facebook', { scope : 'email' }));

    // handle the callback after facebook has authenticated the user
    app.get('/auth/facebook/callback',
        passport.authenticate('facebook', {
            successRedirect : '/home',
            failureRedirect : '/login'
        }));

    // route for logging out
    app.get('/logout', function(req, res) {
        console.log("logout");
        req.session.regenerate(function(){
            req.logout();
            res.redirect('/login');
        });
    });

    app.get('*', function(req, res) {
        res.sendfile('./public/index.html');
    });

}

我还有一个名为AnimalCtrl的控制器,它向我的Express API发出GET请求:

$http({url: '/api/animal/:id', method: 'GET', params : { id: $routeParams.id } })
  .success(function(response) {
    ...
  }).error(function(response){
     console.log("erro "+response);
  });

但是,当我输入网址http://localhost:8080/animal/5429d6fa20348a6178cb1890

时,我收到以下错误
Uncaught SyntaxError: Unexpected token < app.js:1
Uncaught SyntaxError: Unexpected token < animal.js:1
Uncaught Error: [$injector:modulerr] Failed to instantiate module adote due to:
Error: [$injector:nomod] Module 'adote' is not available! You either misspelled the module name or    forgot to load it. 
If registering a module ensure that you specify the dependencies as the second argument.

有点奇怪,我注意到id 5429d6fa20348a6178cb1890被解释为它是一个文件 enter image description here

这是我完整的文件结构:

enter image description here

有人可以帮我这个吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

根据您在github(https://github.com/larissaleite/Routing)上的代码,这是一个更新的答案。 问题出在index.html文件中,替换为:

<script src="js/app.js"></script>

by(见前导/

<script src="/js/app.js"></script>

不要忘记将所有控制器添加到index.html:

<script src="/js/controllers/animal.js"></script>
<script src="/js/controllers/home.js"></script>
<script src="/js/controllers/cadastro.js"></script>

您的index.html'询问'是否有javascript文件,但收到了您的index.html,因为您的服务器无法“解析”您在index.html中提供的路径。使用Chrome开发工具,如果您在询问js / apps.js时查看来自服务器的响应,您会看到它收到index.html 这是由于这些方面:

app.get('*', function(req, res) {
    res.sendfile('./public/index.html');
});

定义视图文件夹(请参阅http://expressjs.com/api.html#app.set

app.set('views', __dirname + '/public/views');

并从您的route.js中删除这些行:

app.get('/home', function(req, res, next) {
    console.log(req.isAuthenticated());
    res.sendfile('./public/views/home.html');
});

app.get('/cadastro', function(req, res, next) {
    res.sendfile('./public/views/cadastro.html');
});

app.get('/animal/:id', function(req, res, next) {
    res.sendfile('./public/views/animal.html')
});

其他一些建议:

  1. 添加.gitignore文件。您不必跟踪node_modules和bower_components文件夹
  2. 我建议您为前端应用使用路由器:请参阅ngRoute或uiRouter