【问题标题】:AngularJS - Failed to instantiate module when passing parameters in urlAngularJS - 在 url 中传递参数时无法实例化模块
【发布时间】:2014-11-24 11:45:03
【问题描述】:

我的 routes.js 文件中定义了以下 URL:

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);
  });

但是,当我输入 url 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 被解释为好像它是一个文件

这是我完整的文件结构:

有人可以帮我解决这个问题吗?

谢谢!

【问题讨论】:

  • 前 2 个错误告诉您您的 javascript 代码中有语法错误。 AngularJs 错误是因为它找不到您定义的 adote 模块——因为由于语法错误,没有加载包含代码的文件。简而言之,修复你的语法错误。
  • 感谢您的评论!你的意思是控制器中的javascript错误吗?控制器唯一拥有的是我在上面发布的代码。我什至试图评论它,但我遇到了同样的问题。我使用相同的结构,并且该模块在我的应用程序的其他页面中被实例化得很好。它与我在 URL 中的参数有什么关系?
  • 您的问题解决了吗?如果没有,我可能会提供帮助。我相信错误在于yoyr express路由而不是角度。 Coukd你分享你的快速路由配置吗?意外字符“
  • 感谢@apairet 的评论!尚未解决 :( 我编辑了问题并包含了我的 routes.js 文件。如果您需要其他任何内容,请告诉我。
  • 请同时发布您的 app.js 文件。请注意,从您的 route.js 文件提供静态文件是非常罕见的。您可以通过定义“views”目录来替换 res.sendfile(xyz.html):app.set('views', config.root + '/views');

标签: angularjs url express url-parameters


【解决方案1】:

根据您在 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

【讨论】:

  • 感谢您的回答,@apairet!我刚刚编辑了这个问题。如果您需要更多信息,请告诉我
  • 我没有设法让它像那样工作。我应该删除所有返回 HTML 文件的路由吗?因为我尝试删除所有这些并且只保留默认的('*'),但它们都不起作用。也许我错过了什么
  • 好吧,这是一个想法。今晚我会更新答案。只是为了确定,你使用什么版本的快递? 3 还是 4?你能展示更多你的 index.html 吗?您还加载了哪些其他脚本?我只看到 app.js,但对您的控制器一无所知。谢谢
  • Express 4. 我为每个 htmls 文件加载不同的控制器。 index.html 只是有一个使用 Facebook 登录的按钮,这就是为什么没有附加控制器的原因。至于其他页面,都可以看到 app.js 及其各自的控制器
  • @LarissaLeite 我更新了答案。抱歉耽搁了。
猜你喜欢
  • 2014-05-30
  • 2014-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-04
  • 2015-04-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多