Git Product home page Git Product logo

mean-machine-code's Introduction

MEAN Machine Code

Code samples for the JavaScript book: MEAN Machine

MEAN Machine

Requirements

Installation Instructions

Installation instructions will vary for each chapter, but if it is a Node/Angular application (all except chapter 11), the following will apply:

  1. Install your Node dependencies: npm install
  2. Start the application nodemon server.js
  3. Visit the application in your browser: http://localhost:8080
  4. Enjoy and learn!

Notice

We work hard to keep the code samples updated with the evolution of technologies mentioned in the book. If you find anything that does not work because of, for example, the usage of a newer and better version of a dependency, please let us know.

mean-machine-code's People

Contributors

bguignebologne avatar gavinpalmer1984 avatar nonameable avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mean-machine-code's Issues

$http.get and posts

Api access from angular to the backend is used like that:

(from authService.js):

return $http.post('/api/authenticate', {
			username: username,
			password: password
		})
			.then(function(data) {
				AuthToken.setToken(data.token);
       			return data;
			});

Try to login and data.token is undefined.
I've checked online and i found that $http.post returns a response object which contains the data object.

I've had to rewrite authService like that:

	return $http.post('/api/authenticate', {
			username: username,
			password: password
		})
			.then(function(response) {
				AuthToken.setToken(response.data.token);
       			return data;
			});

Log in again and response.data.token is now defined.

The same issue affects all api routes: if you fix authService you can log in but the users view is empty

To fix it, modify userCrtl.js from

User.all()
		.then(function(data) {
			// when all the users come back, remove the processing variable
			vm.processing = false;

			// bind the users that come back to vm.users
			vm.users = data;
		});

to:

User.all()
		.then(function(response) {
			// when all the users come back, remove the processing variable
			vm.processing = false;

			// bind the users that come back to vm.users
			vm.users = response.data;
		});

Still need to patch the other views.

17 - User CRM Login

Hi there

I bought the book and moving forward on it. I'm stuck in the login form, since authService.js returns data.data.success ... instead of data.success. When I try to check the property to login the user or show an error message, I can't do it exactly the way the book describes it.

What can I be doing wrong? See files mainCtrl.js and authService.js

mainCtrl.js

angular.module('mainCtrl', [])

.controller('mainController', function($rootScope, $location, Auth) {

    var vm = this;

    vm.loggedIn = Auth.isLoggedIn();

    $rootScope.$on('$routeChangeStart', function() {
        vm.loggedIn = Auth.isLoggedIn();
        Auth.getUser()
            .then(function(data) {
                vm.user = data;
            });
    });

    vm.doLogin = function() {
        vm.processing = true;
        vm.error = '';

        Auth.login(vm.loginData.username, vm.loginData.password)
            .then(function(data) {
                vm.processing = false;
                if (data.success)
                    $location.path('/users');
                else
                    vm.error = data.message;
            });
    };

    vm.doLogout = function() {
        Auth.logout();
        vm.user = {};
        $location.path('/login');
    };
});

authService.js

`angular.module('authService', [])

.factory('Auth', function($http, $q, AuthToken) {
var authFactory = {};

authFactory.login = function(username, password) {
    return $http.post('/api/authenticate', {
        username: username,
        password: password
    })
        .then(function(data) {
            console.log("fede", data.data.token);
            AuthToken.setToken(data.token);
            return data;
        });
};

authFactory.logout = function() {
    Auth.setToken();
};

authFactory.isLoggedIn = function() {
    if (AuthToken.getToken())
        return true;
    else
        return false;
};

authFactory.getUser = function() {
    if (AuthToken.getToken())
        return $http.get('/api/me', { cache: true });
    else
        return $q.reject({ message: 'User has no token.' });
};

return authFactory;

})

.factory('AuthToken', function($window) {
var authTokenFactory = {};

authTokenFactory.getToken = function() {
    return $window.localStorage.getItem('token');
};

authTokenFactory.setToken = function(token) {
    if(token)
        $window.localStorage.setItem('token', token);
    else
        $window.localStorage.removeItem('token');
};

return authTokenFactory;

})

.factory('AuthInterceptor', function($q, AuthToken) {
var interceptorFactory = {};

interceptorFactory.request = function(config) {
    var token = AuthToken.getToken();
    if(token)
        config.headers['x-access-token'] = token;

    return config;
};

interceptorFactory.responseError = function(response) {
    if (response.status == 403) {
        AuthToken.setToken();
        $location.path('/login');
    }
    return $q.reject(response);
};

return interceptorFactory;

});`

User.findById() throws a CastError

The get route in the api (from chapter 10) throws an error when a user id is passed in the url in postman.

Here is the relevant code:

User.findById(req.params.user_id, function (err, user) {
if (err) res.send(err);

        res.json(user);
    });

{
"message": "Cast to ObjectId failed for value "54e17f7d44a911a16653b4b" at path "_id"",
"name": "CastError",
"type": "ObjectId",
"value": "54e17f7d44a911a16653b4b",
"path": "_id"
}

I've tried casting the value from req.params.user_id to an id using mongoose.Types.ObjectId(), but still no luck. This problem happened with the code from the repo as well as my own code.

09-API mongoose trying to open closed connection

I had been working my way through the chapter when I ran into the problem shown below which I've been unable to resolve. I tried several things (including mongoose.disconnect(), using my local mongod) which didn't work. Finally, I just cloned this repo, copied in your version of server.js and experienced the same problem. No amount of googling has provided a solution... what the heck am I doing wrong?

Thanks very much...jon

9 Feb 04:15:04 - [nodemon] starting `node server.js`
events.js:85
      throw er; // Unhandled 'error' event
            ^
Error: Trying to open unclosed connection.
    at NativeConnection.Connection.open (/Users/jseidel/dev/meanjs/mean_api/node_modules/mongoose/lib/connection.js:210:15)
    at Mongoose.connect (/Users/jseidel/dev/meanjs/mean_api/node_modules/mongoose/lib/index.js:212:15)
    at Object.<anonymous> (/Users/jseidel/dev/meanjs/mean_api/server.js:31:10)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3
9 Feb 04:15:04 - [nodemon] app crashed - waiting for file changes before starting...

Stuck on API creation

Fisrt, bought and downloaded PDF (Oct 8th 2016)

The newer versions of mongoose caused a break in code.

However,

I'm stuck now trying to figure out why I can't post a user (create) or get someone. I've decided to use MLAB and I've created a database called 'meanmachinebook'

I know that you created a database with an odd name in the book, and you don't elude to creating any collections, like User, user or users.... so not sure how to post or get from this MLAB database.

From my server.js

`// BASE SETUP
// ======================================

// CALL THE PACKAGES --------------------
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser'); // get body-parser
var morgan = require('morgan'); // used to see requests
var mongoose = require('mongoose');
var User = require('./app/models/user');
var port = process.env.PORT || 8080; // set the port for our app

// APP CONFIGURATION ---------------------
// use body parser so we can grab information from POST requests
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// configure our app to handle CORS requests
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');
next();
});

// log all requests to the console
app.use(morgan('dev'));

// connect to our database (hosted on MLab)
mongoose.connect('mongodb://xxxxxx:[email protected]:53196/meanmachinebook');

// ROUTES FOR OUR API
// ======================================

// basic route for the home page
app.get('/', function(req, res) {
res.send('Welcome to the home page!');
});

// get an instance of the express router
var apiRouter = express.Router();

// middleware to use for all requests
apiRouter.use(function(req, res, next) {
// do logging
console.log('Somebody just came to our app!');

next(); // make sure we go to the next routes and don't stop here

});

// test route to make sure everything is working
// accessed at GET http://localhost:8080/api
apiRouter.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});

// on routes that end in /users
// ----------------------------------------------------
apiRouter.route('/users')

// create a user (accessed at POST http://localhost:8080/users)
.post(function(req, res) {

    var user = new User();      // create a new instance of the User model
    user.name = req.body.name;  // set the users name (comes from the request)
    user.username = req.body.username;  // set the users username (comes from the request)
    user.password = req.body.password;  // set the users password (comes from the request)

    user.save(function(err) {
        if (err) {
            // duplicate entry
            if (err.code == 11000) 
                return res.json({ success: false, message: 'A user with that username already exists. '});
            else 
                return res.send(err);
        }

        // return a message
        res.json({ message: 'User created!' });
    });

})

// get all the users (accessed at GET http://localhost:8080/api/users)
.get(function(req, res) {
    User.find(function(err, users) {
        if (err) return res.send(err);

        // return the users
        res.json(users);
    });
});

// on routes that end in /users/:user_id
// ----------------------------------------------------
apiRouter.route('/users/:user_id')

// get the user with that id
.get(function(req, res) {
    User.findById(req.params.user_id, function(err, user) {
        if (err) return res.send(err);

        // return that user
        res.json(user);
    });
})

// update the user with this id
.put(function(req, res) {
    User.findById(req.params.user_id, function(err, user) {

        if (err) return res.send(err);

        // set the new user information if it exists in the request
        if (req.body.name) user.name = req.body.name;
        if (req.body.username) user.username = req.body.username;
        if (req.body.password) user.password = req.body.password;

        // save the user
        user.save(function(err) {
            if (err) return res.send(err);

            // return a message
            res.json({ message: 'User updated!' });
        });

    });
})

// delete the user with this id
.delete(function(req, res) {
    User.remove({
        _id: req.params.user_id
    }, function(err, user) {
        if (err) return res.send(err);

        res.json({ message: 'Successfully deleted' });
    });
});

// REGISTER OUR ROUTES -------------------------------
app.use('/api', apiRouter);

// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);`

Gulp Nodemon issue

I followed the simple mean application at the end of the book and I have errored - unfortunately - the very last part. I installed nodemon gulp package and when I run gulp I get the following output.

.
.
.

[15:42:57] [nodemon] watching: *.*
[15:42:57] [nodemon] starting `node server.js`

/node_modules/gulp-nodemon/index.js:76
    cp.spawnSync('gulp', tasks, { stdio: [0, 1, 2] })
       ^
TypeError: Object #<Object> has no method 'spawnSync'
    at run (<my dir name>/node_modules/gulp-nodemon/index.js:76:8)
    at <my dir name>node_modules/gulp-nodemon/index.js:58:19

my dir name is the just what I substituted for the whole directory name. Anyone having the same issue?

About 09-node-api

image
image

Even though I follow exactly as the instruction in the book, I do not get the password shown up using Postman. It goes the same whether I use MongoLab or local database with Robomongo.

Any idea about this issue?

Thanks.
Gary

POST Http Issue

I am stuck on the CRUD part of the mean machine book. Whenever I try create a User through Postman it times out and doesn't get any response. However the code compiles and executes and the page exists when I go to localhost:8080. It just doesn't pass the POST request

The code:
// BASE SETUP
// ======================================

//grab the package we need.

var mongoose = require('mongoose');
//replaced connect with createConnetion
mongoose.createConnection('mongodb://localhost/db_name');

// BASE SETUP
// ======================================

// :@jello.modulus....
// CALL THE PACKAGES --------------------
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser'); // get body-parser
var morgan = require('morgan'); // used to see requests
var mongoose = require('mongoose'); // for working w/ our database
var port = process.env.PORT || 8080; // set the port for our app

var User = require('../restful-app/models/user');
//connect to our database (hosted on modulus.io)
mongoose.connect('mongodb://:@jello.modulusmongo.net:27017/byq7Ewim');

// APP CONFIGURATION ---------------------
// use body parser so we can grab information from POST requests
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// configure our app to handle CORS requests
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,
Authorization');
next();
});

// log all requests to the console
app.use(morgan('dev'));

// ROUTES FOR OUR API
// =============================

//route middleware and first route are here

//on routes that end in /users
// ----------------------------------------

var apiRouter = express.Router();
// get an instance of the express Router

apiRouter.route('/users')

//create a user (accessed at POST http://localhost:8080/api/users)
// A post route is created for our application

.post(function(req, res){
//create a new interface of the user model
var user = new User();

//set the users information (comes from the request)
user.name = req.body.name;
user.username = req.body.username;
user.password = req.body.password;

//save the user and check for errors

user.save(function(err) {

if(err) {
//duplicate entry
if(err.code= 11000)
return res.json({ success: false, message: 'A user with that\ username already exists. '});
else
return res.send(err);

}
            res.json({message: 'User created'});
          });

})

// middleware to use for all requests
apiRouter.use(function(req, res, next) {
// do logging
console.log('Somebody just came to our app!');

 // we'll add more to the middleware in Chapter 10

// this is where we will authenticate users

next(); // make sure we go to the next routes and don't stop here
});

// test route to make sure everything is working
// (accessed at GET http://localhost:8080/api)
apiRouter.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});

//more routes for our API will happen here

// REGISTER OUR ROUTES -------------------------------

// all of our routes will be prefixed with /api
app.use('/api', apiRouter);

// more routes for our API will happen here

// basic route for the home page
app.get('/', function(req, res) {
res.send('Welcome to the home page!');
});

// get an instance of the express router
var apiRouter = express.Router();

// test route to make sure everything is working
// accessed at GET http://localhost:8080/api
apiRouter.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});

// more routes for our API will happen here

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', apiRouter);

// START THE SERVER
// ===============================
app.listen(port);
console.log('Magic happens on port ' + port);

The User.js schema code.

// grab the packages that we need for the user model
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt-nodejs');

// user schema
var UserSchema = new Schema({
name: String,
username: { type: String, required: true, index: { unique: true }},
password: { type: String, required: true, select: false }
});

// hash the password before the user is saved
UserSchema.pre('save', function(next) {
var user = this;
16
// hash the password only if the password has been changed or user is new
if (!user.isModified('password')) return next();

// generate the hash
bcrypt.hash(user.password, null, null, function(err, hash) {
if (err) return next(err);

// change the password to the hashed version
user.password = hash;
next();
});
});

// method to compare a given password with the database hash
UserSchema.methods.comparePassword = function(password) {
var user = this;

return bcrypt.compareSync(password, user.password);
};

// return the model
module.exports = mongoose.model('User', UserSchema);

Cloned the Repository: Ran npm intsall in chapter 17: Still doesn't work

I figured out the issue, which is with mongoose new versions i.e >4. If you use mongoose > 4 and use the new .then command in the controllers, its doesn't work. I had to use an old version of mongoose i.e. "mongoose": "~3.8.19", and used . success instead of .then in the controllers, and it worked fine.

Here is the live version on Heroku.

https://user-crm-420.herokuapp.com/

I still would like to know why new versions of mongoose are not working with .then, any explanations.

Just a little fix on the login spinner in chapter 17

I was reading the book and studied the code and found a little mistake.
Not going to make a pull request because of this.

https://github.com/scotch-io/mean-machine-code/blob/master/17-user-crm/public/app/views/pages/login.html#L31

Just replace
<span ng-if="login.processing" class="spinner"><span class="glyphicon glyphicon-repeat"></span></span>

with
<span ng-if="login.processing"><span class="glyphicon glyphicon-repeat spinner"></span></span>

By the way: Thanks for this awesome book!

Error on page 132

In the Angular chapter about Configuring Routes

// inject ngRoute for all our routing needs
angular.module('routerRoutes', ['ngRoute'])

Should be 'routerApp' since that was the name of the app already set in the example.

Chapter 9 - TypeError: object is not a function

Have worked through to this point with no problems. I have checked my code against this repo and it match but I have getting the following error:

TypeError: object is not a function

screen shot 2015-04-11 at 2 58 41 pm

This is refering to this line of code:

var user = new User();

Any help would be much appreciated. Thanks for the great book by the way.

James

chapter 14 - request for clarifications

Not a real issue, just a request for clarifications.

In chapter 14 (Mean Stack Application Structure) you move all api routing code in /app/routes/api.js ; i understand how it works, but there are two points i don't get:

in line 1 you require bodyparser

var bodyParser = require('body-parser'),

but bodyParser is never actually used in api.js

in line 9 you declare module exports passing app and express variables

module.exports = function(app, express) {

but app is never used in api.js

So my question is: are these two (bodyparser and app) needed in some ways without being explicitly called or can they be removed? If they are needed, then why?

17- User CRM Login name cached

Hello,

If you login with one account it shows the username perfectly but if you log out and login back with a different user without closing the browser it shows the user that was logged in before, forcing to press F5 then shows the user correctly, im guessing its not refreshing the view.

Issue with pg. 132 Routing

I am currently going through your tutorial (fantastic by the way), and I have stumbled upon this issue.

screen shot 2016-01-05 at 8 59 54 am

As you can see I am receiving this error that 'routerRoutes is not defined'. Now I had gone through and typed out the code, and then I copy and pasted yours to see if this error persisted. I have made sure to check that all of my files and folders are in the right location.

Any recommendations? Or skip ahead and go to the next section?

MEAN workflow gulpfile js task

Gulp Task 'js' includes both front end and back end (server.js Node code). I am assuming it should just lint the code and not process it further or pipe it to the /dist folder on the front end? Should task 'js' just contain back end code?
There is another task 'scripts' which just contains front end code?

gulp.task('js', function() {
//return gulp.src(['server.js', 'public/app/.js', 'public/app/__/.js'])
return gulp.src(['server.js'])
.pipe(jshint())
.pipe(jshint.reporter('default'))
// .pipe(uglify())
// .pipe(concat())
// .pipe(gulp.dest('/public/dist'));
});

data binding not working in 17-user-crm

on index.html, I have

<li ng-if="main.loggedIn" class="navbar-text">Hello {{ main.user.name }}!</li>

The navbar-text doesn't get updated after I login.

users

However, if I click in the address bar and hit enter it does get updated.

users 1

I thought maybe it was my code, so I downloaded your source and it does the same thing.

Any ideas?

Memory leak caused by Gulpfile's nodemon task.

From gulpfile.js in chapter 19.

gulp.task('nodemon', function() {
  nodemon({
    script: 'server.js',
    ext: 'js less html'
  })
    .on('start', ['watch'])
    .on('change', ['watch'])
    .on('restart', function() {
      console.log('Restarted!');
    });
});

Everytime a file changes, you're triggering watch which attaches additional listeners. After a few restarts, you will exceed the max number of listeners.

This should be rewritten to avoid memory leaks. Just remove the line which starts watch on change. It's redundant since start is triggered on restart anyway. I have made a pull request with the necessary fix.

Not working with UI-ROUTER

Hi! I'm new on MEAN Stack, I was trying to follow your e-book but I got stucked at the point of the Login button with AngularJS in the MEAN app: users manager chapter.

Untill then, evertihing was working just perfectly.

I'm following all the steps but with ui-router insted, I guess this may cause some problems with the $http.post in here:
` authFactory.login = function(username, password) {

    // return the promise object and its data
    return $http.post('/api/authenticate', {
        username: username,
        password: password
    })
        .then(function(data) {
            AuthToken.setToken(data.token);
            return data;
        });
};`

I really don't understand why the button doesn't do anything :(

any idea why could it be? @sevilayha

19-mean-workflow gulp 'scripts' & 'angular' tasks redundant by accident?

I have a question about 2 gulp tasks that seem appear to be (partially) redundant:

Both the 'scripts' and the 'angular' tasks grab js files from the same location, and in fact the only difference between these two tasks is the 'angular' task includes ngAnnotate in it's pipeline.

I'm a little confused, could this be a mistake?

If I am reading the book right the all.js file generated by the 'scripts' task is supposed to contain all of our front end Angular files, and the app.js file generated by the 'angular' task should contain our angular libs. If that is the case shouldn't the 'angular' task be grabbing js files from inside of the assets folder instead of the app folder?

login username on navbar

Hello,

After cloned and run this app, I found a bug: after login using username john and logout, re-login using different username jane will provide username john on navbar. It supposed to be username jane on navbar, isn't it? CMIIW

Potential Security Issue

👋 Hello, we've received a report for a potential critical severity security issue in your repository.

Next Steps

1️⃣ Visit https://huntr.dev/bounties/1-other-scotch-io/mean-machine-code for more advisory information.

2️⃣ Sign-up to validate or speak to the researcher for more assistance.

3️⃣ Propose a patch or outsource it to our community.


Confused or need more help?

  • Join us on our Discord and a member of our team will be happy to help! 🤗

  • Speak to a member of our team: @JamieSlome


This issue was automatically generated by huntr.dev - a bug bounty board for securing open source code.

Interceptor not triggered whan comming from /api/whatever

Hi! thanx for the book and the material, it's been really helpfull.
I was just following the ebook and "translating" it into "ui-router way", I think it's far more easier.

Well, the problem is that I created the User CRM and the replicated almost the same for a bikes model. Everything is ok in the public routes, but once I'm under /api route if I navigate trough the buttons is ok. But when I push
app comp.zip
the url from the browser
for example: localhost:8080/api/bikes it responds : "success": false, "message": "No token provided
There's a Token, I checked it out in dev tools and works fine in POSTMAN.

NOTE: My front.routes.js is pointing to the very same url: /api/bikes. If not it allows to enter to the non logged in users.

I guess the problem is that the interceptor it's not being triggered so I doesn't catch the token. And I don't know why is not being triggered and neither how force to do so.

@sevilayha I hope you can help me. I allways follow your posts :)

Please have a look I spent almost a week and couldn't find the way out. :(

I attached here the involved files. Anything you need just let me know.
Thanx again.
app comp.zip

'username not found' in chapter 10

First, I writhe all the code myself, than I tryed to copy it from the book but the problem doesn't go away :(

apiRouter.post('/authenticate', function (req, res) {
    // find the user
    User.findOne({
        username: req.body.username
    }).select('name username password').exec(function (err, user) {

        if (err) throw err;

        // no user with that username was found
        if (!user) {
            res.json({
                success: false,
                message: 'Authentication failed. User not found.'
            });
        } else if (user) {

            // check if password matches
            var validPassword = user.comparePassword(req.body.password);
            if (!validPassword) {
                res.json({
                    success: false,
                    message: 'Authentication failed. Wrong password.'
                });
            } else {

                // if user is found and password is right
                // create a token
                var token = jwt.sign({
                    name: user.name,
                    username: user.username
                }, superSecret, {
                    expiresInMinutes: 1440 // expires in 24 hours
                });

                // return the information including token as JSON
                res.json({
                    success: true,
                    message: 'Enjoy your token!',
                    token: token
                });
            }
        }
    });
});

image

username and password are correct.

Also I found out that the findOne method returns 'null'.

Hi!!! your book is a great resource, but just two questions...

In the authService the { cache: true } expedient is ok for performance but if I logout and then I log in with a new user the link on the nav bar remains with the name of the previous logged user. Refreshing the page solves the issue.

In the mainCtrl (code below) the vm.user obj is only available inside the promise but outside is undefined. Is there a way to make it available to the other functions of the controller?

    // get user information on page load
        Auth.getUser()
            .then(function(data) {
                vm.user = data.data;
                console.log("inside: ", vm.user); // obj...
            }); 
        console.log("outside: ", vm.user);      // undefined
    });

Bye for now, ciao

Bug in page 131 of book

Hello guys!

I'm currently eating through the book at an unhealthy pace. It's a truly awesome book, love your work.

Anyhow, found a small bug in page 131

Screenshot of the page:

image

At this point you guys mention it should work, however it won't because earlier you configured server.js to handle all GET requests and direct them to index.html:

image

And then from that point until the first screenshot you don't edit server.js again, which means that when the browser requests the app.js and app-routes.js with a GET request it gets served index.html instead of our javascript files.

To solve this I went into my server.js and edited it a bit like so:

// Set the public folder to serve public assets
app.use(express.static(__dirname + "/public/views"));

// Set up our one route to the index.html file
app.get("/", function(req, res) {
    res.sendFile(path.join(__dirname + "/public/views/index.html"));
});

Just a small comment, figured you might want to know and I figure you do change it a after that screenshot (In page 131). But since you show working screenshots and the site itself won't work at that point that might be disconcerting for less technically inclined users.

Thanks for writing this book, it's truly amazing.

Will keep eating through the book, and report if I find anything similar again, have a great day!

Cannot find module .app/modules/user

Dear all,

I tried to find a solution for the below error

but no success so far unfortunately. I have cloned the repo and compared the provided code with mine but can't spot the problem. I also checked the access rights of folders and all but I'm stuck. I am just starting with coding so if you have further general advice how to best debug please feel free to add this to your answer. Cheers!

module.js:339
throw err;
^

Error: Cannot find module './app/models/user'
at Function.Module._resolveFilename (module.js:337:15)
at Function.Module._load (module.js:287:25)
at Module.require (module.js:366:17)
at require (module.js:385:17)
at Object. (/Users/cph/Public/Coding/hacks/actioncy-learn-to-code/app/server.js:10:18)
at Module._compile (module.js:425:26)
at Object.Module._extensions..js (module.js:432:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:311:12)
at Function.Module.runMain (module.js:457:10)
at startup (node.js:136:18)
at node.js:972:3

A bug in authService of the 17-user-crm

At line 23 and 24 of authService.js, use "data.data.token" and "return data.data" instead, because the "data" object has many other properties and the "data" property of it is what we need here.

nodejs v 4

Hello. I want to buy ur book. But I want to know, right now nodejs is v4.1 and he ea6 from box. It is not problem if I start to learn with old version.?

Gulp & Linting JS page 235

Got the error "Error: Cannot find module 'jshint/src/cli'"

Had to install jshint along with gulp-jshint.

npm install --save-dev jshint gulp-jshint

10-node-authentication route middleware prevents user creation

I might be wrong but shouldn't the block which begins like this to create a user:

// on routes that end in /users
// ----------------------------------------------------
apiRouter.route('/users')

    // create a user (accessed at POST http://localhost:8080/users)
    .post(function(req, res) {

be placed before the route middleware to verify a token? :

In User CRM chapter, catchall route in server.js is catching requests for js files in index.html

Took me a while to track down the source of this issue, but now that I have I don't know how to continue with the rest of the book.

In the server.js file, as it's constructed in previous chapters, we're instructed to write this catchall route for front-end routing just before we start the app listening:

app.get('*', function (req, res) {
    res.sendFile(path.join(__dirname + '/public/app/views/index.html'));
});

And in the index.html file, we're instructed to call our angular services, controllers, and app files thusly:

<!-- controllers -->
<script src="app/controllers/mainCtrl.js"></script>
<script src="app/controllers/userCtrl.js"></script>

<!-- services -->
<script src="app/services/authService.js"></script>
<script src="app/services/userService.js"></script>

<!-- main Angular app files -->
<script src="app/app.routes.js"></script>
<script src="app/app.js"></script>

Because of the catchall route node intercepts these requests and sends back index.html, like we told it to. But we need that catchall route in there to forward requests to the frontend so... what to do isn't clear.

But I could also be missing something.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.