500内部服务器错误,表示反应mongo mern堆栈

您好我有我的反应组件中的registry单的麻烦,我用mongodb,这里是我的服务器,路由和注册组件我得到这个错误

xhr.js:178 POST http://localhost:3000/api/user/ 500 (Internal Server Error) dispatchXhrRequest @ xhr.js:178 xhrAdapter @ xhr.js:12 dispatchRequest @ dispatchRequest.js:59 Promise resolved (async) request @ Axios.js:51 Axios.(anonymous function) @ Axios.js:71 wrap @ bind.js:9 saveUser @ API.js:18 Signup._this.handleSubmit @ Signup.js:47 callCallback @ react-dom.development.js:540 invokeGuardedCallbackDev @ react-dom.development.js:579 invokeGuardedCallback @ react-dom.development.js:436 invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:450 executeDispatch @ react-dom.development.js:834 executeDispatchesInOrder @ react-dom.development.js:853 executeDispatchesAndRelease @ react-dom.development.js:954 executeDispatchesAndReleaseTopLevel @ react-dom.development.js:965 forEachAccumulated @ react-dom.development.js:933 processEventQueue @ react-dom.development.js:1105 runEventQueueInBatch @ react-dom.development.js:3600 handleTopLevel @ react-dom.development.js:3609 handleTopLevelImpl @ react-dom.development.js:3340 batchedUpdates @ react-dom.development.js:11066 batchedUpdates @ react-dom.development.js:2323 dispatchEvent @ react-dom.development.js:3414 API.js:20 Error: Request failed with status code 500 at createError (createError.js:16) at settle (settle.js:18) at XMLHttpRequest.handleLoad (xhr.js:77) xhr.js:178 XHR failed loading: POST "http://localhost:3000/api/user/". 

我不知道我是否连接到数据库,尽pipemongo客户端正在工作。

server.js

 const express = require("express"); const path = require("path"); const bodyParser = require("body-parser"); const cookieParser = require("cookie-parser"); const mongoose = require("mongoose"); const passport = require("passport"); const LocalStrategy = require("passport-local").Strategy; const PORT = process.env.PORT || 3001; const routes = require("./routes"); const app = express(); const User = require("./models/users"); //authentication packages const session = require('express-session'); const MongoStore = require('connect-mongo')(session); const bcrypt = require('bcrypt'); // Configure body parser for AJAX requests app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); //set up cookies for sessions app.use(cookieParser()); // Serve up static assets (usually on heroku) if (process.env.NODE_ENV === "production") { app.use(express.static("client/build")); } // Add routes, both API and view app.use(routes); // Set up promises with mongoose mongoose.Promise = global.Promise; // Connect to the Mongo DB mongoose.connect(process.env.MONGODB_URI || "mongodb://localhost/airlane", {useMongoClient: true}); //initialize passport and express-session app.use(session({ secret: 'holla hoops', //random key store: new MongoStore({ url: MONGODB_URI }), resave: false, saveUninitialized: false })); app.use(passport.initialize()); app.use(passport.session()); //setting passport for log in, log out and signup passport.serializeUser((user, done) => { done(null, user); }); passport.deserializeUser((user, done) => { db.User.findOne({ _id: user.userID }).then((user, error) => { if (error) { done(error); } done(null, user); }); }); passport.use( new LocalStrategy( { usernameField: "email" //change default username to email }, (email, password, done) => { console.log(email); console.log(password); // return done(null, "LOGIN SUCCESSFUL!"); db.User.findOne({ email }).then((user, error) => { if (error) { done(error); } const hashPass = user.password; console.log("Hash: " + hashPass); if (hashPass.length === 0) { //essentially, if no user info is returned done(null, false); } else { //... else, run the bycrypt compare method to authenticate //bcrypt de-hash bcrypt.compare(password, hashPass, (err, response) => { if (response === true) { console.log("Successful login!"); return done(null, { userID: user._id }); } else { console.log("Unsuccessful login!"); return done(null, false); } }); } }); } ) ); // Send every request to the React app // Define any API routes before this runs app.get("*", function(req, res) { res.sendFile(path.join(__dirname, "./client/build/index.html")); }); app.listen(PORT, function() { console.log(`🌎 ==> Server now on port ${PORT}!`); }); userController.js 

 const db = require("../models"); const path = require("path"); //methods to connect to mongo db module.exports = { findAll: function(req, res) { db .find(console.log(res)) .then(dbModel => res.json(dbModel)) .catch(err => res.status(422).json(err)); }, findById: function(req, res) { db .findById(req.params.id) .then(dbModel => res.json(dbModel)) .catch(err => res.status(422).json(err)); }, create: function(req, res) { console.log("Running create: "); db .create(req.body) .then(dbModel => res.json(dbModel)) .catch(err => res.status(422).json(err)); }, update: function(req, res) { db .findOneAndUpdate({ _id: req.params.id }, dbModel) .then(dbModel => res.json(dbModel)) .catch(err => res.status(422).json(err));; }, remove: function(req, res) { db .findById({ _id: req.params.id }) .then(function(dbModel) { dbModel.remove();}) .then(dbModel => res.json(dbModel)) .catch(err => res.status(422).json(err)); } }; // // Dependencies // // ============================================================= // const passport = require('passport'); // const db = require("../models"); // const path = require("path"); // const bcrypt = require('bcrypt'); // const session = require('express-session'); // const authenticationMiddleware = require('../utils/authenticationMiddleware'); // const saltRounds = 10; // // Routes // // ============================================================= // module.exports = (app) => { // // send basic index.html file at root // app.get("/", (req, res) => { // //console log user info if any // console.log(req.user); // console.log(req.isAuthenticated()); // res.send("../public/index.html") // }); // // register new user // app.post("/register", (req, res) => { // const email = req.body.email; // const password = req.body.password; // bcrypt.hash(password, saltRounds, (err, hash) => { // const newUser = { // email, // password: hash // }; // db.User // .create(newUser) // .then((user) => { // //console.log(user); // console.log("This is the userID for new user:"); // console.log(user._id); // db.User // .findOne({ _id: user._id }) // .then((signedInUser, error) => { // if (error) throw (error); // console.log("NEW USER CREATED: "); // console.log(signedInUser); // //deserialize config is expecting user.userID to be accessible // req.login({userID: signedInUser._id}, (err) => { // res.redirect("/"); // }) // }) // }) // .catch((err) => { // // If an error occurred, send it to the client // console.log(err); // res.redirect("/"); // }); // }); // }); // app.post("/login", passport.authenticate('local', { // successRedirect: "/profile", //if login was successful, redirect to profile page // failureRedirect: "/" //if login unseccussful, redirect to homepage // }), ); // app.post("/logout", (req, res) => { // console.log(`Logging out user:`); // console.log(req.user); // req.session.destroy( (err) => { // req.logout(); // res.send(true); // }) // }); // // profile page. Only renders if authentication is verified, if not, redirect to root // app.get("/profile", authenticationMiddleware(), (req, res) => { // //console log user info if any // console.log(req.user); // console.log(req.isAuthenticated()); // res.redirect("/") // }); // }; 

Axios Api.js

 import axios from "axios"; export default { // Gets all user getUsers: () => { return axios.get("/api/user"); }, // Gets the user with the given id getUser: (id) => { return axios.get("/api/user/" + id); }, // Deletes the user with the given id deleteUser: (id) => { return axios.delete("/api/user/" + id); }, // Saves a user to the database saveUser: (userData) => { return axios.post("/api/user/", userData) .then(console.log(userData)) .catch(err =>{console.log(err)}) } }; 

反应注册组件

 import React, { Component } from "react"; import { Button, FormGroup, FormControl, ControlLabel, Modal } from "react-bootstrap"; import API from "../Utils/API"; class Signup extends Component { constructor(props) { super(props); this.state = { showModal: false, firstName: "", lastName: "", email: "", password: "", passwordConf: "", userCreated: Date }; this.open = this.open.bind(this); this.close = this.close.bind(this); } open = () => { this.setState({ showModal: true }); }; close = () => { this.setState({ showModal: false }); }; // Handles updating component state when the user types into the input field handleChange = event => { console.log(event.target.value); const { name, value } = event.target; this.setState({ [name]: value }); }; //when the form is submitted, use the API to save a user handleSubmit = () => { API.saveUser({ firstName: this.state.firstName, lastName: this.state.lastName, email: this.state.email, password: this.state.password, userCreated: Date.now }) .then(console.log(this.state)) .catch(err => console.log(err)); }; render() { return <div> <div onClick={this.open}>Sign Up</div> <Modal show={this.state.showModal} onHide={this.close}> <Modal.Header closeButton> <Modal.Title>Registeration</Modal.Title> </Modal.Header> <Modal.Body> <div> <form > <FormGroup> <ControlLabel htmlFor="firstName"> First Name </ControlLabel> <FormControl name="firstName" type="text" placeholder="ex: Michael" onChange={this.handleChange} /> </FormGroup> <FormGroup> <ControlLabel htmlFor="lastName">Last Name</ControlLabel> <FormControl name="lastName" type="text" placeholder="ex: Smith" onChange={this.handleChange} /> </FormGroup> <FormGroup> <ControlLabel htmlFor="email">Eamil</ControlLabel> <FormControl name="email" type="email" placeholder="ex: johnSmith@email.com" onChange={this.handleChange} /> </FormGroup> <FormGroup> <ControlLabel htmlFor="password">Password</ControlLabel> <FormControl name="password" type="password" placeholder="New Password!" onChange={this.handleChange} /> </FormGroup> <FormGroup> <ControlLabel htmlFor="passwordconf"> Confrim Password </ControlLabel> <FormControl name="passwordConf" type="password" placeholder="confirm new password" onChange={this.handleChange} /> </FormGroup> <Button type="submit" value="submit" onClick={this.handleSubmit}> Submit </Button> </form> </div> </Modal.Body> <Modal.Footer> <div> <Button>Facebook</Button> <Button>Google</Button> </div> <Button onClick={this.close}>Close</Button> </Modal.Footer> </Modal> </div>; } } export default Signup; 

它不断给我500内部服务器错误