2017-06-02 49 views
1

我尝试使用快递创建用户。 我在帕拉姆URL通过邮差做一个POST请求所有的新用户数据的直通以下网址:使用Express&Mongoose无法管理存储新用户

localhost:3000/users/register?first_name=1&last_name=1&email=1&password=123456&country=1&city=1&street=1&number=1 

而且我在控制台上收到此错误:

There was an erorrError: Illegal arguments: undefined, string

在我创建的student.js模型文件夹,它是一个用户。

const mongoose = require('mongoose'); 
const Schema = mongoose.Schema; 
const bcrypt = require('bcryptjs'); 


const StudentSchema = new Schema({ 
    first_name: String, 
    last_name: String, 
    email:{ 
     type: String, 
     required: true, 
     unique: true 
    }, 
    password: { 
     type: String, 
     required: true 
    }, 
    address: 
     { country: String, 
      city: String, 
      street: String, 
      number: Number 
     }, 
    created_at: Date, 
    updated_at: Date 
}); 
StudentSchema.pre('save', function(next) { 
    var currentDate = new Date(); 
    this.updated_at = currentDate; 
    if (!this.created_at) 
     this.created_at = currentDate; 

    next(); 
}); 
var Student = mongoose.model('Student', StudentSchema); 
module.exports = Student; 

module.exports.addStudent = function(newStudent, callback){ 
    bcrypt.genSalt(10, function(err, salt) { 
     bcrypt.hash(newStudent.password, salt, function(err, hash) { 
      if(err) { 
       console.log(hash); 
       **console.log("There was an erorr" + err);** 
      }else { 
       newStudent.password = hash; 
       newStudent.save(callback); 
      } 
     }); 
    }); 
}; 

在路由文件夹的用户路由器:

var express = require('express'); 
var router = express.Router(); 
var Student = require('../models/student'); 
var mongodb = require('mongodb'); 

router.post('/register', function(req, res, next) { 
    var newStudent =new Student({ 
     first_name: req.body.first_name, 
     last_name: req.body.last_name, 
     email: req.body.email, 
     password: req.body.password, 
     address: 
      { 
       country: req.body.country, 
       city: req.body.city, 
       street: req.body.street, 
       number: req.body.number 
      } 
    }); 

    Student.addStudent(newStudent, function(err,user) { 
    if(err){ 
     res.json({success: false, msg:'Failed to register user'}); 
    } else { 
     res.json({success: true, msg:'User registered'}); 
    } 
    }); 
}); 

router.get('/newstudent', function(req, res) { 
    res.render('newstudent', { title: 'Add student' }); 
}); 

module.exports = router; 

我markered代码行制动器, “**”

回答

0

您在邮​​差与查询参数发送数据(其显示在url中),并期望提取req.body中的数据。

您可以更改其中的一个(在邮递员发送请求正文中,或者在快速提取查询参数中),但不建议在URL中以类似的用户名/密码发送敏感数据,因为它是可见的并且不太安全。

所以,你应该改变你的邮差将数据发送到身体像这样的方式:

enter image description here

+0

工作,谢谢!!!! –

+0

@ModiNavon很高兴我帮了忙,请接受我的答案,如果你认为它解决了它。 –