am using passport to handle the log in process in my app but, am not using a server side route which is a submitted from instead, am using an xhr post, but because of that i got an issue that i couldn't determine.
here is the code of my app.js:
module.exports = function(db){
var express = require('express');
var mongoose = require('mongoose'),
passport = require('passport'),
LocalStrategy = require('passport-local').Strategy;
var env = process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var app = express();
var config = require('./config/config')[env];
require('./config/express')(app);
require('./config/db');
var User = mongoose.model('User');
passport.use(new LocalStrategy(
function(username, password, done){
User.findOne({userName:userName}).exec(function(err, user){
if(user){
return done(null, user);
console.log('found the user');
}else{
return done(null, false);
console.log('user not found');
}
})// query of findOne
}
));
passport.serializeUser(function(user, done){
if(user){
done(null, user._id);
}
});
passport.deserializeUser(function(id, done){
User.findOne({_id:id}).exec(function(err, user){
if(user){
return done(null, user);
}else
return done (null, false);
})
})
require('./config/routes')(app);
return app;
}
which is i don't get any of the log messages in my console, made me think i never query the database.
and here is the code of my route that i require at the end of the app.js
app.post('/login', function(req, res, next){
var auth=passport.authenticate('local', function(err, user){
if(err){return next(err);}
if(!user){res.send({success: false})}
req.logIn(user, function(err){
if(err){return next(err); }
res.send({success: true, user:user});
})
})
auth(req, res, next);
})
i handle the client side log in using angular.js so here is the controller code :
angular.module('app').controller('mvLoginCtrl', function($scope, $http){
$scope.signin = function(username, password){
$http.post('/login', {username:username, password:password}).then(function(response){
if(response.data.success){
console.log('logged in');
}else{
console.log('failed to log in');
}
})
}
})
the only message i got in my browser console is the one i logged in my mvLoginCtrl controller "failed to log in" and i can't tell where my code fail and if it query the data base or not .but each attempted to log in with exist username i get the fail message any help or explanation is appreciated.
express.js located ./config/express.js
var express = require('express');
var http = require('http');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var passport = require('passport');
module.exports = function(app){
// view engine setup
app.set('views', path.join(__dirname, '../views'));
//app.set('views', config.rootPath + 'views');
app.set('view engine', 'jade');
app.use(favicon());
app.use(logger('dev'));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(express.session({secret: 'myapp mobile unicorns'}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, '../public')));
//app.use(express.static(config.rootPath + 'public'));
/*
*Middleware to modifiy the header.
*/
app.use(function(req,res,next){
res.set ('myapp-Powered-By' , 'mycompany');
next();
});
}
the log of the response object returned from the post request in the mvLoginCtrl controller
Object {data: "<!DOCTYPE html><html><head><title></title>
<link re…/app/admin/mvPushCtrl.js"></script></body></html>",
status: 200, headers: function, config: Object, statusText: "OK"}config:
Objectdata: "<!DOCTYPE html><html><head><title></title>
<link rel="stylesheet" href="/stylesheets/style.css">
<link rel="stylesheet" href="/vendor/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="/vendor/toastr/toastr.min.css">
</head><body ng-app="app"><h1>userName is not defined</h1><h2></h2><pre>ReferenceError: userName is not defined?
at Strategy._verify (C:\Users\M-Mouallem\Desktop\mySpace\sandBox\myapp\app.js:21:36)?
at Strategy.authenticate (C:\Users\M-Mouallem\Desktop\mySpace\sandBox\myapp\node_modules\passport-local\lib\strategy.js:90:12)?
at attempt (C:\Users\M-Mouallem\Desktop\mySpace\sandBox\myapp\node_modules\passport\lib\middleware\authenticate.js:337:16)?
at authenticate (C:\Users\M-Mouallem\Desktop\mySpace\sandBox\myapp\node_modules\passport\lib\middleware\authenticate.js:338:7)?
at C:\Users\M-Mouallem\Desktop\mySpace\sandBox\myapp\config\routes.js:24:6?
at callbacks (C:\Users\M-Mouallem\Desktop\mySpace\sandBox\myapp\node_modules\express\lib\router\index.js:164:37)?
at param (C:\Users\M-Mouallem\Desktop\mySpace\sandBox\myapp\node_modules\express\lib\router\index.js:138:11)?
at pass (C:\Users\M-Mouallem\Desktop\mySpace\sandBox\myapp\node_modules\express\lib\router\index.js:145:5)?
at Router._dispatch (C:\Users\M-Mouallem\Desktop\mySpace\sandBox\myapp\node_modules\express\lib\router\index.js:173:5)?
at Object.router (C:\Users\M-Mouallem\Desktop\mySpace\sandBox\myapp\node_modules\express\lib\router\index.js:33:10)</pre><script type="text/javascript" src="/vendor/jquery/dist/jquery.min.js"></script><script type="text/javascript" src="/vendor/bootstrap/dist/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/vendor/toastr/toastr.js"></script><script type="text/javascript" src="/vendor/angular/angular.min.js"></script>
<script type="text/javascript" src="/vendor/angular-resource/angular-resource.min.js"></script><script type="text/javascript" src="/vendor/angular-route/angular-route.min.js"></script>
<script type="text/javascript" src="/app/app.js"></script><script type="text/javascript" src="/app/main/mvMainCtrl.js"></script>
<script type="text/javascript" src="/app/account/mvLoginCtrl.js"></script><script type="text/javascript" src="/app/account/mvIdentity.js"></script>
<script type="text/javascript" src="/app/common/mvNotifier.js"></script><script type="text/javascript" src="/app/account/mvAuth.js"></script>
<script type="text/javascript" src="/app/admin/mvPushCtrl.js"></script></body></html>
"headers: function (c){a||(a=vc(b));return c?a[I(c)]||null:a}status: 200statusText: "OK"__proto__: Object mvLoginCtrl.js:22
failed to log in
Related
I'm starting learning Express and Angularjs. In the project, I want to render HTML at the server side and bind data via Angularjs but it didnt work. I saw that ng-repeat is disable in browser
<body ng-app="photoApp" class="ng-scope">
<h1>Express</h1>
<p>Welcome to Express</p>
<!-- ngView: -->
<div ng-view="" class="ng-scope">
<div id="photos" class="ng-scope">
<!-- ngRepeat: photo in vm.photos -->
</div>
</div>
</body>
, therefore no data is showed. Please help me to fix that, thanks in advanced!
Project Structure
photo
--public
----javascript
------lib
------photoApp.js
--routes
----index.js
----photo.js
--views
----partials
------photo-list.pug
----error.pug
----index.pug
----layout.pug
--app.js
Server-side code:
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var photos = require('./routes/photos');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use('/photos', photos);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/partials/:name', function(req, res, next){
var name = req.params.name;
res.render('partials/' + name);
});
module.exports = router;
photos.js
var express = require('express');
var router = express.Router();
var photos = [];
photos.push({
name: 'Node.js Logo',
path: 'http://nodejs.org/images/logos/nodejs-green.png'
});
photos.push({
name: 'Ryan Speaking',
path: 'http://nodejs.org/images/ryan-speaker.jpg'
});
router.get('/api/get-all', function(req, res) {
res.json(photos);
});
router.get('/', function(req, res) {
res.render('photos');
});
module.exports = router;
layout.pug
doctype html
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
script(src='javascripts/lib/angular.js')
script(src='javascripts/lib/angular-route.js')
script(src='javascripts/photoApp.js')
body(ng-app="photoApp")
block content
index.pug
extends layout
block content
h1= title
p Welcome to #{title}
div(ng-view)
photo-list.pug
#photos
.photos(ng-repeat="photo in vm.photos")
h2 {{photo.name}}
img(src="{{photo.path}}")
Client-side code:
photoApp.js
var photoApp = angular.module('photoApp', ['ngRoute']);
photoApp.controller('PhotoListController', PhotoListController);
photoApp.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/', {
templateUrl: 'partials/photo-list',
controller: 'PhotoListController',
controllerAs: 'vm'
})
.otherwise({
redirectTo: '/'
});
}]);
function PhotoListController($scope, $http) {
var vm = this;
vm.getAllPhotos = getAllPhotos;
function getAllPhotos(){
$http.get('/photos/api/get-all')
.success(function(response) { vm.photos = response.photos; })
.error(function() { console.log('Error when getting all photos'); });
}
}
I try to create a SPA with angular on a node/express server. Please bear with me, I am confused. View engine is ejs. On my app.js I have
var routes = require('./routes/index');
app.use('/', routes.list);
index.js contains
exports.list = function(req, res){
res.render('index', {
title: 'Home'
});
};
so it can render index.ejs that contains
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="./public/javascripts/angular.min.js"></script>
<script src="./public/javascripts/angular-route.min.js"></script>
<script>
var app = angular.module('app', ['ngRoute']);
app.config(function ($routeProvider) {
// configure the routes
$routeProvider
.when('/', {
// route for the home page
templateUrl: './views/home.ejs',
controller: 'homeController'
})
.when(' /about', {
// route for the about page
templateUrl: './views/about.ejs',
controller: 'aboutController'
})
)}
app.controller('homeController', function ($scope) {
$scope.message = 'Welcome to my home page!';
});
app.controller('aboutController', function ($scope) {
$scope.message = 'Find out more about me.';
});
</script>
<title><%= title %></title>
<div ng-view></div>
<li>Home</li>
<li>About</li>
home.ejs and about.ejs are like
<h1>About Page</h1>
<p>{{ message }}</p>
1- I cannot load the angular.min.js and angular-route.min.js. I get angular is not defined for the var app = angular.module('app', ['ngRoute']); line in index.ejs file and Unexpected token < for <!DOCTYPE html> on the same file.
2- home.ejs and about.ejs dont load
3- I replace with app.use('/#', routes.list); on app.js and <a href="#"> <a href="#about"> on the index.ejs and I get error 404. Why the # character on the URL causes problems?
4- Should I also create routes for about like var about = require('./routes/about'); and app.use('/about', about.list);? Or is an SPA, so routes are not necessary because they will cause page loads?
Sorry for the big question.
Thanks in advance
UPDATE
on the index.ejs file I changed the app to sp , so no conflicts occur, but the same problems remain.
UPDATE 2
the whole app.js is
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes.list);
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
app.listen(4800);
module.exports = app;
I am trying to move my angular controller code into a separate file and the JS file is throwing errors like angular not recognised. It was working when the controller was in the same file
html file
<!DOCTYPE html>
<html ng-app="demo">
<head>
<title>title </title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<script src='//ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js'>
<script src='//ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular-resource.min.js'>
<script src="public/js/ang.js"></script>
</head>
<body ng-controller="democontroller">
<h1>title </h1>
<p>Welcome to title </p>
</body>
</html>
ang.js file
var app = angular.module('demo', []);
app.controller("democontroller", function($scope,$http,$window) {
alert("hi");
});
node's app.js file
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
app.listen(8000, function(){
console.log("ready on port 8000");
});
module.exports = app;
We figured it out in the chat I believe the code was missing closing </script> tags.
I have a web application that uses OAuth 2 running on Node. Using EJS templates I was able to properly create a workflow that prompts a user to login, authenticate, and then performs a "GetUser" GET command and dumps the output to the screen. Recently I have attempted to remove EJS and want to get AnguarJS working.
Currently I have removed EJS and implemented Angular, however with angular many strange things happen and I cannot figure out why!
When my user clicks "Login" they are supposed to be brought to another website that they login to using OAuth 2. This process works fine on Node with EJS, however with angular my controller loads, the correct partial is loaded but there is no data. Reviewing this process with Chrome DEV tools I see the following error
XMLHttpRequest cannot load http://website/oauth/authorize?...
No 'Access-Control-Allow-Origin'
header is present on the requested resource.
Origin 'http://localhost:8080' is therefore not allowed access.
What is even weirder is that in the network tab I can see the correct Request URL! If I copy and paste this URL into another tab my "GetUser" command executes, but then node crashes and my page fails.
I have attempted different browsers, enabling CORS, and configuring CORS. I know the issue is with Angular as I can successfully use the same code with EJS. I have put my Angular code below, any assistance would be appreciated!
Server Side
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var config = require('./config.js')
var passport = require('passport');
var OAuth2Strategy = require('passport-oauth').OAuth2Strategy;
var session = require('express-session');
var index = require('./routes/index');
var login = require('./routes/login');
var logout = require('./routes/logout');
passport.serializeUser(function(user, done) {done(null, user);
});
passport.deserializeUser(function(obj, done) {done(null, obj);
});
// config
passport.use('Company', new OAuth2Strategy({
authorizationURL: config.authorizationURL,
tokenURL: config.tokenURL,
clientID: config.clientID,
clientSecret: config.clientSecret,
callbackURL: config.callbackURL,
passReqToCallback: true
},
function(req, accessToken, refreshToken, profile, done) {
process.nextTick(function () {
// store access token
req.session.accessToken=accessToken;
return done(null, profile);
});
}
));
var app = express();
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({secret: 'secret'}))
app.use(passport.initialize());
app.use(passport.session());
// configure Express
app.get('/api/login', ensureAuthenticated, login.execute);
app.get('/api/logout', logout.execute);
app.get('/auth/company',
passport.authenticate('company'),
function(req, res){
});
app.get('/auth/company/callback',
passport.authenticate('company', { failureRedirect: '/' }),
function(req, res) {
console.log('comming back from company');
res.redirect('/api/login');
});
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/')
}
module.exports = app;
Login.js (Route)
var request = require('request');
exports.execute = function (req, res) {
console.log(req.user);
console.log(req.app.get('accessToken'));
var accessToken = req.session.accessToken;
console.log("accessToken in loginjs" + accessToken);
if(accessToken){
var options = {
url: 'http://company/getCurrentUser',
headers: {
Authorization: 'bearer ' + accessToken
}
};
request.get(options, function(error, response, body){
if(error){
console.log('login.js inside error' + error);
res.json('login.js inside error' + error);
return;
}
console.log(response);
res.render('account', { user: response });
});
}else{
res.render('account', { user: req.user });
}
}
www
var debug = require('debug')('myApp');
var app = require('../app');
app.set('port', process.env.PORT || 8080);
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
Client Side
app.js (angular)##
angular.module('MyApp', ['ngCookies', 'ngResource', 'ngMessages', 'ngRoute', 'mgcrea.ngStrap'])
.config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/', {
templateUrl: 'views/home.html',
controller: 'MainCtrl'
})
.when('/login', {
templateUrl: 'views/account.html',
controller: 'LoginCtrl'
})
.otherwise({
redirectTo: '/'
});
}]);
login.js Controller
angular.module('MyApp')
.controller('LoginCtrl', ['$scope', 'Auth', function($scope, Auth){
var user = Auth.authorize();
$scope.user=user;
$scope.headingTitle='Logged in page';
}]);
auth.js Service
angular.module('MyApp')
.factory('Auth', ['$resource', function($resource){
return $resource('/auth/company', null,
{
'authorize': {method: 'GET'}
});
}]);
home.html Partial to route to company Oauth2
<div class="container">
<div class="panel panel-default">
<div class="panel-body">
<div class="text-center">
<p>Login via Company</p>
</div>
</div>
</div>
</div>
account.html Partial to show User data
<div>
<h1>You are logged in.</h1>
Go home<br>
Logout<br>
<p>Dumping User: {{user}}</p>
</div>
edit
I have tried the follow with no success
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X- Requested-With, Access-Control-Allow-Origin');
res.header("Access-Control-Max-Age", "86400"); // 24 hours
if ('OPTIONS' == req.method) {
res.send(200);
}
else {
next();
}
};
var app = express();
app.use(allowCrossDomain);
Edit 2:
I did some more digging and also noticed that Angular is not listed as initiating the second URL. Its almost as if angular is re-routing the callback URL as a separate call of its own. I have attached the below picture
Edit 3:
I have continued to work on this but cannot figure out why Angular is stripping out my headers! Any Additional input would be greatly appreciated!
Edit 4:
I found that I can have the webpage load the route instead of Angular by adding the code below to the Login button. After doing this and pointing the link to /auth/company rather than to api/login I get successfully redirected to the login page!
<div class="container">
<div class="panel panel-default">
<div class="panel-body">
<div class="text-center">
<p><a target="_self" href="/auth/company">Login via Company</a></p>
</div>
</div>
</div>
</div>
However the battle continues, as after I login I get redirected to the below picture - inside of node I receive the data however the application dies and does not show the /account page.
Can you try enabling CORS in express server
npm install cors
app.js
var cors = require('cors')
var app = express()
app.use(cors())
Reference to this link
I never user $resource and instead use $http. You have to enable 'withCredentials' on the client's request as well. I also think you DON'T need if('OPTIONS' == req.method) as I've never needed this. One more note, you can't use a wildcard domain '*' with credentials. You'd have to explicitly allow origin 'http://127.0.0.1:8080' and make sure you're cookie uses the 127 and not localhost (you'll run into problems with cookies otherwise).
var req = {
method:'POST',
url: 'users/login',
data: {
},
withCredentials:true
};
$http(req).then(function (response) {
if( response.data.success ){
}
if( response.data.error){
}
});
I have the following URL defined in my routes.js file:
app.get('/animal/:id', function(req, res, next) {
res.sendfile('./public/views/animal.html')
});
This is 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'];
})
This is the link for index.html (there's not much here): https://gist.github.com/larissaleite/6280ca1bcd9886e7b253
This is where I do all the configuration on my application:
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);
This is routes.js complete:
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');
});
}
I also have a controller called AnimalCtrl, which makes a GET request to my Express API:
$http({url: '/api/animal/:id', method: 'GET', params : { id: $routeParams.id } })
.success(function(response) {
...
}).error(function(response){
console.log("erro "+response);
});
However, I get the following error when I type in the 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.
What is a bit strange that I noticed that the id 5429d6fa20348a6178cb1890 is interpreted as if it was a file
This is my complete file structure:
Can someone help me with this?
Thank you!
Based on your code on github (https://github.com/larissaleite/Routing), here is an updated answer.
The issue is in your index.html file, replace:
<script src="js/app.js"></script>
by (see the leading /)
<script src="/js/app.js"></script>
Do not forget to add all your controllers to your index.html:
<script src="/js/controllers/animal.js"></script>
<script src="/js/controllers/home.js"></script>
<script src="/js/controllers/cadastro.js"></script>
Your index.html 'asks' for javascript files but receives your index.html because your server cannot 'resolve' the path your provide in your index.html. Using Chrome Dev Tools, if you look at the response from the server when asked for js/apps.js you should see it receives index.html
It is due to these lines:
app.get('*', function(req, res) {
res.sendfile('./public/index.html');
});
Define a view folder (see http://expressjs.com/api.html#app.set)
app.set('views', __dirname + '/public/views');
and remove these lines from your 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')
});
Some other advices:
Add a .gitignore file. You do not have to track node_modules and bower_components folders
I would recommend you to use a router for your frontend app: see ngRoute or uiRouter