Не удается сохранить нового пользователя с Express & Mongoose

1

Я пытаюсь создать пользователя с выражением. Я делаю запрос POST со всеми новыми пользовательскими данными в URL-адресе параметра через Postman по следующему URL-адресу:

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

И я получаю эту ошибку на консоли:

Был erorrError: незаконные аргументы: 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;

Я маркировал тормоза линии кода с помощью "**"

Теги:
express

1 ответ

0
Лучший ответ

Вы отправляете данные в Postman с параметрами запроса (которые отображаются в URL- req.body) и ожидаете извлечь данные в req.body.

Вы можете изменить один из них (либо в блоке запроса отправки почты, либо в экспресс-извлечении параметров запроса), но не рекомендуется отправлять конфиденциальные данные в виде имени пользователя/пароля в URL-адресе, потому что он видимый и менее безопасный.

Поэтому вы должны изменить способ отправки данных в Postman на тело следующим образом:

Изображение 174551

  • 0
    Работаем, СПАСИБО !!!!
  • 0
    @ModiNavon Рад, что я помог, пожалуйста, примите мой ответ, если вы думаете, что это помогло.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню