Я создаю приложение MEAN Stack и пытаюсь создать нового пользователя для добавления в мою MongoDB.Тестируя эту функцию на Почтальоне, я продолжаю получать 500 внутренних ошибок сервера.Я console.log после создания newUser в user-contoller.js, но отображается только {_id: 5c700e93cb5c320d18bc285}.
app.js
//
Dependency or module imports
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors');
const helmet = require('helmet');
const passport = require('passport');
//Used to use enviroment variables to connect to DB
require('dotenv').config();
const dbconfig = require('./config/database');
//Use this for now - have to change for development and production testing
var url ="mongodb://localhost:27017/DB-Dev" || 3000;
//Connecting to MongoDB - locally, development, testing, and production -- Changing dbconfig files
mongoose.Promise = global.Promise;
mongoose.connect(url, {
useCreateIndex: true,
useNewUrlParser: true
});
// On database connection
mongoose.connection.on('connected', () => {
console.log('Connected to database');
});
// If database connection errors
mongoose.connection.on('error', (err) => {
console.log('Database error: ' + err);
//winston.error('Failed to connect to database)
})
//Create express application
const app = express();
//Use helmet to set some http security headers
app.use(helmet());
// Imports for routing classes
const userRoutes = require('./routes/user-routes');
//Port for server to listen on - may change in the future
const port = 3000;
//CORS default allows request from anywhere - set origins or routes
app.use(cors());
//set static folder for client side files
app.use(express.static(path.join(__dirname, '../public')));
//Body parser middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization"
);
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PATCH, PUT, DELETE, OPTIONS"
);
next();
});
//Passport middleware
// app.use(passport.initialize());
// app.use(passport.session());
// //Import passport config file
// require('./config/passport')(passport);
//Default all routes to the homepage
app.get('*',(req,res) => {
res.render(path.join(__dirname, '../angular-src/src/index.html'));
});
//Route handling done here
app.use('/users',helmet.noCache(), userRoutes);
//If there is an error, returns a 500 error
app.use((err, req, res, next) => {
if(err) {
return res.sendStatus(500);
}
next();
});
//Start Server
app.listen(port, () => {
console.log("Server started on: " + port);
}).setTimeout = 300000; //Timeout after 5 minutes
user-model.js
// Import modules and configuration files
const mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator');
// User schema
const userSchema = mongoose.Schema({
firstName: {
type: String,
required: true,
},
lastName: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true
},
password: {
type:String,
required: true,
},
});
//Using this will check for duplicate database entries
userSchema.plugin(uniqueValidator);
module.exports = mongoose.model("User", userSchema);
user-controller.js
//Import dependencies here needed to complete middleware implementation
const crypto = require('crypto');
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const validationResult = require("express-validator");
const User = require('../models/user-model');
exports.createUser = (req, res, next) => {
bcrypt.hash(req.body.password, 10).then(hash => {
const newUser = new User({
firstName: req.body.firstName,
lastname: req.body.lastname,
email: req.body.email,
password: hash
});
newUser.save().then(result => {
res.status(201).json({
message: "User has been created",
result: result
});
})
.catch(err => {
res.status(500).json({
message: "Invalid authentication credentials"
});
});
});
} // End of createUser middleware
user-rout.js
// Import dependencies
const express = require('express');
const { check } = require('express-validator/check');
// Imported controller files
const UserController = require('../controller/user-controller');
// Create a new instance of Router
const router = express.Router();
// TO - DO
//register route follows /users/register
//middle checks array is from express-validator library. checks strings to see if they meet requirements also sanitizes html with the .escape()
router.post("/register",
UserController.createUser
);
//TO-DO: Authenticate
//TO-DO: Resend Verification Email
//TO-DO: Verify Account
//TO-Do: Get User Profile
module.exports = router;