无法读取null的属性“ firstname”

时间:2019-07-01 20:47:10

标签: node.js

我想注册一个用户。我将数据保存到数据库,但是之后出现错误

  

无法读取null的属性“ firstname”。本来以为主体可以为空,但是当我键入console.log(req.body);时,它显示了保存的数据。我认为问题是我注册后该会话已关闭,但我不知道如何解决。   如果有人可以帮忙,我会很高兴!   有人

var express = require("express");
var app = express();
var path = require("path");
const https = require("https");
const fs = require("fs");
var mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/WeSports");
var connection = mongoose.connection;
var bodyParser = require("body-parser");
var passport = require("passport");
var LocalStrategy = require("passport-local");
var User = require("./models/user.js");
const multer = require("multer");

const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, "./uploads/");
  },
  filename: function(req, file, cb) {
    cb(null, new Date().toISOString() + file.originalname);
  }
});

const fileFilter = (req, file, cb) => {
  // reject a file
  if (file.mimetype === "image/jpeg" || file.mimetype === "image/png") {
    cb(null, true);
  } else {
    cb(null, false);
  }
};

const upload = multer({
  storage: storage,
  limits: {
    fileSize: 1024 * 1024 * 5
  },
  fileFilter: fileFilter
});

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use("/uploads", express.static("uploads"));
app.use(
  require("express-session")({
    secret: "Logged in",
    resave: false,
    saveUninitialized: false
  })
);

connection.once("open", function() {
  connection.db.collection("user-data", function(err, collection) {
    if (err) {
      console.error("An error occurred connecting to MongoDB: ", err);
    } else {
      collection.find({}).toArray(function(err, data) {
        if (err) {
          console.error("An error occurred connecting to MongoDB: ", err);
        } else {
          console.log(data); // it will print your collection data
        }
      });
    }
  });
});

app.set("view engine", "ejs");
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use("/", express.static(path.join(__dirname, "public")));
app.get("/", function(req, res) {
  var tagline = "Hello";
  res.render("Login", {
    tagline: tagline
  });
});

app.post("/insert", upload.single("picture"), function(req, res) {
  var user = {
    picture: req.file.path,
    firstname: req.body.firstname,
    name: req.body.name,
    city: req.body.city,
    birthday: req.body.birthday,
    phonenumber: req.body.phonenumber,
    email: req.body.email,
    aboutme: req.body.aboutme
  };
  var data = new User(user);
  data.save();
  console.log(req.body);
  User.register(
    new User({
      picture: req.file.path,
      username: req.body.username,
      firstname: req.body.firstname,
      name: req.body.name,
      city: req.body.city,
      birthday: req.body.birthday,
      phonenumber: req.body.phonenumber,
      _id: req.body.email,
      aboutme: req.body.aboutme
    }),
    req.body.password,
    function(err, User) {
      if (err) {
        console.log(err);
        return res.render("SignIn");
      } //user stragety
      passport.authenticate("local")(req, res, function() {
        res.redirect("/profile/" + req.body.email); //once the user sign
        up;
      });
    }
  );
  console.log(req.body);
});

app.get("/SignIn", function(req, res) {
  User.find().then(function(doc) {
    res.render("SignIn", { user: doc });
  });
});

app.post(
  "/",
  passport.authenticate("local", {
    failureRedirect: "/"
  }),
  (req, res) => {
    User.findOne({ username: req.body.username }, function(err, obj) {
      console.log(obj);
      console.log(obj._id);
      res.redirect("dashboard/" + obj._id);
    });
  }
);

var isLoggedIn = function(req, res, next) {
  if (req.isAuthenticated()) {
    return next();
  }
  res.redirect("/");
};

/*function(req, res){
res.send("User is "+ req.user.id);
});*/
app.param("id", function(req, res, next, _id) {
  User.findById(_id, function(err, doc) {
    if (err) res.json(err);
    else {
      req.userId = doc;
      next();
    }
  });
});
/* app.get('dashboard', (req, res, next) => {
upload.findOne({_id: req.params.id}, (err, image) => {
if (err) return res.sendStatus(404);
fs.createReadStream(path.resolve('./uploads', image.filename)).pipe(res);
});
});*/
app.get("/dashboard/:id", isLoggedIn, function(req, res) {
  res.render("dashboard", { user: req.userId });
});

app.get("/profile/:id", isLoggedIn, function(req, res) {
  res.render("profile", { user: req.userId });
});
/*app.get('/loggedin/:id', isLoggedIn, function(req, res){
        res.render("/profile/"+req.body.email); 
});
*/

app.get("/Users", function(req, res) {
  User.find().then(function(doc) {
    res.render("Users", { user: doc });
  });
});

//app.get("/Profil",isLoggedIn, function(req, res){
//if (req.session && req.session.username !== true) {
//  User.find()
//.then(function(doc) {
//res.render('Profil', {items: doc});
//    });
//    }
//        console.log( req.sessionID);
//});

/*app.post("/", passport.authenticate("local",{
successRedirect:"/Profil",
failureRedirect:"/"
})*/

是的,没错,我使用multipart / form-data,因为我想上传并显示图像。我没有上传图片就尝试过。它可以,但是现在我不知道如何实现上传图片。

<form action='/insert' method='post' enctype="multipart/form-data" class="inhalte-werden-zentriert">
    <!--Einleitung des Formulars-->

    <p>add profile picture:<br>
        <label for="file"></label>
        <input class="button" type="file" name="picture" accept="image/png, 
image/jpeg" />
    </p>
    <label for="username"></label>
    </br>
    <input type="text" name="username" placeholder="username" required autofocus="autofocus" pattern="[a-zA-Z]{2,}" id="username"><br>
    <label for="firstname"></label>
    </br>
    <input type="text" autofocus name="firstname" placeholder="firstname" pattern="[a-zA-Z]{2,}" id="firstname"><br>
    <!--Definition des einzeiligen Eingabefelds "Vorname" mit Platzhalter und 
Autofokus + verpflichtendes Feld-->

    <label for="name"></label>
    </br>
    <input type="text" name="name" placeholder="name" id="name" required pattern="[a-zA-Z]{2,}"><br>
    <!--Definition des einzeiligen Eingabefelds "Nachname" mit Platzhalter + 
verpflichtendes Feld-->

    <label for="city"></label>
    </br>
    <input type="text" name="city" placeholder="city" id="city" required pattern="[a-zA-Z]{2,}"><br>
    <!--Definition des einzeiligen Eingabefelds "Wohnort" mit Platzhalter-->

    <label for="birthday"></label>
    </br>
    <input type="date" name="birthday" id="birthday" placeholder="TT.MM.JJJJ" required><br>

    <label for="phonenumber"></label>
    </br>
    <input type="tel" pattern="[0-9]{1,}" name="phonenumber" id="phonenumber" placeholder="phonenumber"><br>
    <!--Definition des einzeiligen Eingabefelds "Telefonnummer" mit Platzhalter 
und Zahlen im Bereich von 0-9-->

    <label for="email"></label>
    </br>
    <input type="email" name="email" id="email" placeholder="email" required>
    <br>
    <!--Definition des einzeiligen Eingabefelds "eMail" mit Platzhalter + 
verpflichtendes Feld-->

    <label for="password"></label>
    </br>
    <input type="password" id="password" name="password" placeholder="password" required><br>
    <label for="aboutme"></label>
    </br>
    <textarea name="aboutme" id="aboutme" rows="6" cols="30" placeholder="aboutme" required></textarea><br>
    <!--Textbereich mit 6 Reihen und 30 Spalten + Platzhalter-->
    <input class="abschicken" type="submit" value="Save" />
    <!--einzeiliges Eingabefeld "Abschicken"-->
</form>

0 个答案:

没有答案