Mongodb -User验证失败

时间:2016-07-05 00:50:39

标签: javascript mongodb authentication mongoose

我正在学习mongodb,但我正在跑到这堵墙,我不知道如何解决它。请帮忙!之前有用,但是这次我发帖请求时我在Postman"用户验证"中得到了这个错误信息。 enter image description here

var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;
var bcrypt      = require('bcrypt-nodejs');


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

UserSchema.pre('save', function(next) {
  var user = this;

  if (!user.isModified('password')) return next();

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

    user.password = hash;
    next();
  });
});

UserSchema.methods.comparePassword = function(password) {
  var user = this;

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

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

var express = require('express');
var app = express();
var bodyParser = require("body-parser");
var morgan = require('morgan');
var mongoose = require('mongoose');
var port = process.env.PORT || 8080;
var User = require('./app/models/user');


app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());


app.use(function(req,res,next){
  res.setHeader('Acess-control-allow-Origin', '*');
  res.setHeader('Acess-control-Allow-Methods', 'GET, POST');
  res.setHeader('Acess-Control-Allow-Headers', 'X-Requested-With, content-type,\Authorization');
  next();
});

app.use(morgan('dev'));

mongoose.connect('mongodb://localhost:27017/myDatabase');

app.get('/', function(req, res){
  res.send('Welcome to thome page');
});

var apiRouter = express.Router();

apiRouter.use(function(req, res, next){
  console.log('Somebody just came to our app');

  next();
});

apiRouter.get('/', function(req, res){
  res.json({message: 'Hooray! Welcome to our api1'});
});

app.use('/api', apiRouter);

apiRouter.route('/users')

         .post(function(req,res){

           var user = new User();

           user.name = req.body.name;
           user.username = req.body.username;
           user.password = req.body.password;

           user.save(function(err){
             if(err){
               if(err.code == 1000)
                 return res.json({success: false, message: "A user with that username already exists"});
               else
                 return res.send(err);
             }
               res.json({message: "User created"});
           });
         });


app.listen(port);
console.log("Magic happens on port " + port);

2 个答案:

答案 0 :(得分:1)

我也和邮递员有这个问题。 然后我决定使用原始数据而不是 x-www-form-urlencoded Json(application / json)标头。 在您的情况下,您可以像这样使用它:

{"name" : "Holly", 
"username" : "Hollylawly",
"password" : "supersecret"}

the image for postman req

答案 1 :(得分:0)

我通过重新安装邮递员来修复。

谢谢你们花时间回答这个问题。

感谢。