2014-09-30 3 views
1

내 routes.js에 정의 된 다음 URL은 파일에 있습니다 :AngularJS와 - 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); 

이3210 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'); 
    }); 

} 

나는 또한 나의 익스프레스 API에 GET 요청을하게 AnimalCtrl라는 컨트롤러가 있습니다 그러나

$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. 
나는 그것이 파일 인 것처럼 아이디 5429d6fa20348a6178cb1890 해석하는 것으로 나타났습니다 것이 조금 이상하다 무엇

enter image description here

이 내 전체 파일 구조입니다 :

enter image description here

사람이 좀 도와 줄래 ?

감사합니다.

+0

첫 번째 두 오류는 당신이 구문 오류가 있음을 말하고있다 당신의 자바 스크립트 코드. AngularJs 오류는 구문 적 오류로 인해 코드가있는 파일이로드되지 않았기 때문에 사용자가 정의한 'adote'모듈을 찾을 수 없기 때문에 발생합니다. 즉, 구문 오류를 수정하십시오. – JoseM

+0

코멘트 주셔서 감사합니다! 컨트롤러에서 자바 스크립트 오류가 발생 했습니까? 컨트롤러에있는 유일한 것은 위에서 게시 한 코드입니다. 나는 심지어 그것을 논평하려고 노력했다. 그러나 나는 같은 문제를 가지고있다. 동일한 구조를 사용하고 모듈은 응용 프로그램의 다른 페이지에서 인스턴스화됩니다. URL에있는 매개 변수와 어떤 관련이 있습니까? –

+0

문제가 해결 되었습니까? 그렇지 않으면 도움을 줄 수 있습니다. 나는 오류가 yoyr express routing에 있다고 생각하며 각도가 아니라고 생각한다. 쿠로하 특급 라우팅 구성을 공유 하시겠습니까? 예상치 못한 문자 '<'는 올바른 경로를 찾을 수 없어 표현하는 index.html 파일에서 온 것 같습니다. 감사합니다. – apairet

답변

0

github (https://github.com/larissaleite/Routing)의 코드를 기반으로 다음은 업데이트 된 답변입니다. 문제는 당신의 index.html 파일에 대체 :

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

를하여 (참조 선도 /)

<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은 귀하의 서버가 귀하의 index.html에서 제공 한 경로를 '해결할 수 없으므로 javascript 파일을 요청하지만 귀하의 index.html을받습니다. (

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

가보기 폴더를 정의 : JS을 요청했을 때 서버의 응답을 보면, 크롬 개발 도구를 사용하여/당신이이 라인에 기인는 가 index.html을 받아 볼 수 apps.js http://expressjs.com/api.html#app.set 참조)

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

이 행을 경로에서 제거하십시오.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
+0

감사합니다. 더 많은 정보가 필요하다면 알려주세요 –

+0

이렇게 작동하도록 만들지는 못했지만 HTML 파일을 반환하는 모든 경로를 제거해야합니까? 모든 것을 제거하고 그냥 기본 ('*')을 남겨 뒀지 만 둘 다 작동하지 않았다. 어쩌면 내가 뭔가를 놓치고있다. –

+0

좋아,이게 무슨 생각이야. 나는 오늘 밤 대답을 업데이트 할 것이다. 어떤 익스프레스 버전을 사용합니까? 3 또는 4? dex.html? 어떤 다른 스크립트를로드합니까? 나는 app.js 만 보지만 컨트롤러에 대해서는 nithing. Thx – apairet

관련 문제