2015-01-21 6 views
0

Я следую в справочнике по проверке узла MEAN machine.Почему моя проверка узла не работает в этом POST?

Вот их исходный код: https://github.com/scotch-io/mean-machine-code/blob/master/10-node-authentication/server.js Я в принципе есть все для apiRouter.post('/authenticate', части

API,

экспресс-работают, за исключением: http://localhost:8615/api/users будет возвращать список пользователей из scotch.io в MongoDB

enter image description here

Ниже приведен API для/api/пользователей:

apiRouter.route('/users') 

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

    // create a new instance 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); 
     } 

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

}) 

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

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

Вот мой user.js Schema Пользователь

// SCHEMAS ------------------------------------ 
// user schema 
var UserSchema = new Schema({ 
    name: String, 
    username: { type: String, required: true, index: { unique: true }}, 
    password: { type: String, required: true, select: false } 
    //^select false will not return passwords 
}); 


// hash the password before the user is saved 
UserSchema.pre('save', function(next) { 
    var user = this; 

    // PUT username 
    if (!user.isModified('username')) return next(); 

    // PUT name 
    if (!user.isModified('name')) return next(); 

    // hash the password only if the password has been changed or user is new 
    if (!user.isModifited('password')) return next(); 

    // generate the salt 
    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(); 
    }); 
}); 

ИЗ КНИГИ:

Create a Sample User

First, we need to make sure that we even have a user to authenticate since towards the end of last chapter, we deleted everyone. Let’s create the user using the POST http://localhost:8080/api/users route we created in our API to add a user to our database.

We will send a POST request with the following information: Name Chris Username chris Password supersecret

Я использую Почтальон для добавления нового пользователя, как вы можете видеть, что я поставил в ключ/значение пары для имени пользователя и пароля, однако получаю сообщение об ошибке сказав «Не удалось выполнить проверку» «имя пользователя требуется» «требуется пароль»:

enter image description here


UPDATE, я просто попытался х-WWW-форм-urlencoded и получил следующее сообщение об ошибке

GET /api/users 200 66.141 ms - 655 
••• API CRUD hit ••• 

/Users/leongaban/NodeDallas/projects/awesome-test/app/models/user.js:27 
    if (!user.isModifited('password')) return next(); 
     ^
TypeError: Object { password: 'supersecret', 
    username: 'Chris', 
    name: 'chris', 
    _id: 54c001dc4ee4028c18e61334 } has no method 'isModifited' 
at model.UserSchema.methods.comparePassword.user (/Users/leongaban/NodeDallas/projects/awesome-test/app/models/user.js:27:12) 

Скриншот ошибки в Почтальон: https://s3.amazonaws.com/f.cl.ly/items/1M0M392M0E3b2i430I1n/Image%202015-01-21%20at%201.45.51%20PM.png

ответ

1

попробовать х-WWW-форм-urlencoded в почтальона, который будет делать.

+0

Это не сработает, мы хотим нажать объект (JSON). Если вы хотите найти своего пользователя в req.body на своей серверной стороне, вы должны передать этого пользователя в Postman исходным вводом (как я сказал в своем первом комментарии). – jlouazel

+0

Я просто попробовал это, и получил другую ошибку. Обновил мой вопрос с подробностями ... спасибо за то, что посмотрел! Идти попробовать отладить это сейчас ... –

+1

Это сработало! После того, как я исправил пропущенную в моей модели User 'if (! User.isModifited ('password')) return next(); \t^ ТипError: Object {password: 'supersecret',' isModified * –

0

Вы хотите нажать JSON на сервер. Выберите raw и установите тип данных в JSON.

Тогда вам просто нужно написать своего пользователя в формате JSON со всеми его полями здесь.

{ 
    "name": "Chris", 
    "username": "chris", 
    "password": "supersecret" 
} 
+0

thx, только что пробовал, но все еще не прошел проверку :(, просто добавил ссылку на исходный код на мой вопрос https://github.com/scotch-io/mean-machine-code/blob/master/10-node-authentication /server.js –