Javascript 为什么我不能创建一个用户?

Javascript 为什么我不能创建一个用户?,javascript,node.js,express,mongoose,postman,Javascript,Node.js,Express,Mongoose,Postman,我正在尝试使用node.js和mongoose设置一个注册和登录服务器。所以我创建了一个用户模型和一个用户路由。有人能找到我为什么不能创建用户的错误吗。我在POST:localhost:3000/users/register下连接到Postman 我的用户模型: const mongoose = require('mongoose'); const uniqueValidator = require('mongoose-unique-validator'); const bcrypt = req

我正在尝试使用node.js和mongoose设置一个注册和登录服务器。所以我创建了一个用户模型和一个用户路由。有人能找到我为什么不能创建用户的错误吗。我在POST:localhost:3000/users/register下连接到Postman

我的用户模型:

const mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator');
const bcrypt = require('bcryptjs');

const UserSchema = new mongoose.Schema({
  email: {
    type: String,
    required: true,
    minlength: 1,
    trim: true, //calls .trim() on the value to get rid of whitespace
    unique: true, //note that the unique option is not a validator; we use mongoose-unique-validator to enforce it
  },
  password: {
    type: String,
    required: true,
    minlength: 8,
  },
});

//this enforces emails to be unique!
UserSchema.plugin(uniqueValidator);

//this function will be called before a document is saved
UserSchema.pre('save', function(next) {
  let user = this;

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

  //we generate the salt using 12 rounds and then use that salt with the received password string to generate our hash
  bcrypt
    .genSalt(12)
    .then((salt) => {
      return bcrypt.hash(user.password, salt);
    })
    .then((hash) => {
      user.password = hash;
      next();
    })
    .catch((err) => next(err));
});

module.exports = mongoose.model('User', UserSchema);
我的用户:

const express = require('express');
const bcrypt = require('bcryptjs');

const User = require('../models/user');

const router = express.Router();

//util function to check if a string is a valid email address
const isEmail = (email) => {
  if (typeof email !== 'string') {
    return false;
  }
  const emailRegex = /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/;

  return emailRegex.test(email);
};

router.post('/register', async (req, res) => {
  try {
    const { email, password } = req.body;
    if (!isEmail(email)) {
      throw new Error('Email must be a valid email address.');
    }
    if (typeof password !== 'string') {
      throw new Error('Password must be a string.');
    }
    const user = new User({ email, password });
    const persistedUser = await user.save();

    res.status(201).json({
      title: 'User Registration Successful',
      detail: 'Successfully registered new user',
    });
  } catch (err) {
    res.status(400).json({
      errors: [
        {
          title: 'Registration Error',
          detail: 'Something went wrong during registration process.',
          errorMessage: err.message,
        },
      ],
    });
  }
});

router.post('/login', async (req, res) => {
    try {
      const { email, password } = req.body;
      if (!isEmail(email)) {
        return res.status(400).json({
          errors: [
            {
              title: 'Bad Request',
              detail: 'Email must be a valid email address',
            },
          ],
        });
      }
      if (typeof password !== 'string') {
        return res.status(400).json({
          errors: [
            {
              title: 'Bad Request',
              detail: 'Password must be a string',
            },
          ],
        });
      }
      //queries database to find a user with the received email
      const user = await User.findOne({ email });
      if (!user) {
        throw new Error();
      }
  
      //using bcrypt to compare passwords
      const passwordValidated = await bcrypt.compare(password, user.password);
      if (!passwordValidated) {
        throw new Error();
      }
  
      res.json({
        title: 'Login Successful',
        detail: 'Successfully validated user credentials',
      });
    } catch (err) {
      res.status(401).json({
        errors: [
          {
            title: 'Invalid Credentials',
            detail: 'Check email and password combination',
            errorMessage: err.message,
          },
        ],
      });
    }
  });
  
  module.exports = router;
我的服务器:

const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const mongoose = require('mongoose');
const dotenv = require("dotenv");
const app = express();
dotenv.config();


//other imports
const usersRoute = require('./routes/users');

//other app.use statements

//connect to db
mongoose.connect(

    process.env.DB_CONNECTION,
  { useNewUrlParser: true,
    useUnifiedTopology: true},
  
    () => console.log('Database connected')
  );
  
  mongoose.Promise = global.Promise;

const port = process.env.PORT || 3000;

//sets up the middleware for parsing the bodies and cookies off of the requests
app.use(bodyParser.json());
app.use(cookieParser());

app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

module.exports = { app };
我只得到这个

Cannot POST /users/register

您没有在服务器文件中指定路径前缀。您应该定义:

app.use("/users", usersRoute );

{“errors”:[{“title”:“Registration Error”,“detail”:“在注册过程中出现了一些错误。”,“errorMessage”:“无法对'req.body'的属性'email'进行分解,因为它未定义。”}]}现在我得到了这个。