Req.flash(errors)不显示-NodeJS 5.7.0

时间:2016-03-07 18:03:52

标签: javascript node.js ejs

当用户输入已在数据库中的电子邮件时,我试图让用户知道该帐户电子邮件已经注册。 我从mongo db得到正确的错误,但我不想显示所有垃圾。我希望它只是在我的注册页面上显示我的错误,表单上写着“此电子邮件地址已经注册”。

MongoDB响应:

MongoError: E11000 duplicate key error index: jcommerce.users.$email_1 dup key: { : "james12345@gmail.com" }
   at Function.MongoError.create (C:\jcommerce\node_modules\mongodb-core\lib\error.js:31:11)
   at toError (C:\jcommerce\node_modules\mongodb\lib\utils.js:114:22)
   at C:\jcommerce\node_modules\mongodb\lib\collection.js:616:23
   at handleCallback (C:\jcommerce\node_modules\mongodb\lib\utils.js:96:12)
   at C:\jcommerce\node_modules\mongodb\lib\bulk\unordered.js:470:9
   at handleCallback (C:\jcommerce\node_modules\mongodb\lib\utils.js:96:12)
   at resultHandler (C:\jcommerce\node_modules\mongodb\lib\bulk\unordered.js:417:5)
   at commandCallback (C:\jcommerce\node_modules\mongodb-core\lib\topologies\server.js:936:9)
   at Callbacks.emit (C:\jcommerce\node_modules\mongodb-core\lib\topologies\server.js:116:3)
   at null.messageHandler (C:\jcommerce\node_modules\mongodb-core\lib\topologies\server.js:282:23)
   at Socket.<anonymous> (C:\jcommerce\node_modules\mongodb-core\lib\connection\connection.js:273:22)
   at emitOne (events.js:90:13)
   at Socket.emit (events.js:182:7)
   at readableAddChunk (_stream_readable.js:153:18)
   at Socket.Readable.push (_stream_readable.js:111:10)
   at TCP.onread (net.js:529:20)

路线等级

var router = require('express').Router();
var User = require('../models/user')

router.get('/signup', function (req, res, next) {
    res.render('accounts/signup', {
        errors: req.flash('errors')
    });
});

router.post('/signup', function(req, res, next) {
        var user = new User();

        user.profile.name = req.body.name;
        user.email = req.body.email;
        user.password = req.body.password;

        // Validate
        User.findOne({email: req.body.email}, function (err, existingUser) {
            if (existingUser) {
                req.flash('errors', 'Account with that email address already exists');
                return res.redirect('/signup');
            }
            else {
                // save user to database
                user.save(function(err, user) {
                    if (err) {
                        return next(err);
                    }

                    return res.redirect('/');


                });
            }
        }); // Mongoose method find one document in db
});

module.exports = router;

EJS

    <% layout('layout') -%>

<div class="row">
    <div class="col-lg-6 col-md-offset-3">

      <% if (errors.length > 0) { %>
        <div class="alert alert-danger alert-dismissible"> 
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
            </button>
            <%= errors %>
            </div>
     <%  } %>

        <form method="post">
            <h1> Signup! </h1>
            <div class="form-group">
            <label="name"> Name: </label>
            <input type="text" class="form-control" name="name">
            </div>
            <div class="form-group">
                <label="name"> Email: </label>
                <input type="email" class="form-control" name="email">
            </div>
            <div class="form-group">
                <label="name"> Password: </label>
                <input type="passwod" class="form-control" name="password">
            </div>
            <button type="submit" class="btn btn-success"> Submit</button>
        </form>
    </div>
</div>

Server.js AKA app.js //需要我们想要使用的库

var express = require('express');
var morgan = require('morgan');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var ejs = require('ejs');
var engine = require('ejs-mate');
var session = require('express-session');
var cookieParser = require('cookie-parser'); // parses cookies and put it on the request object in the middleware
var flash = require('express-flash');

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

// App is reffering to express objects, bc we want to use express objects
var app = express();

mongoose.connect('mongodbconnectionstring', function (err) {
    if (err) {
        console.log(err);
    }
    else
    {
        console.log("Connected to the database");
    }
});

//Middleware - logs requests in cmd
app.use(express.static(__dirname + '/public'));
app.use(morgan('dev'));
app.use(bodyParser.json()); // Express can parse data format
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser());
app.use(session({
    resave: true,
    saveUninitialized: true,
    secret: "James@@@@#"
}));
app.use(flash());
app.engine('ejs', engine)
app.set('view engine', 'ejs');


// body parser takes the body of request and parses it -> Format encoded or raw data

var mainRoutes = require('./routes/main');
var userRoutes = require('./routes/user');
app.use(mainRoutes); // Express is using main routes
app.use(userRoutes);




// Listen on port number 3000 ,
app.listen(3000, function (err) {
  if (err) {
    throw err;
  }
  console.log("Server is Running on port 3000");
});

2 个答案:

答案 0 :(得分:0)

错误源于这一行:

user.email = req.body.email;

这是因为req.body.emailundefined,这意味着电子邮件不是唯一的。您应该验证向/signup发送的请求是否与来自客户端的数据一起发送。

答案 1 :(得分:0)

我只是要检查一下  exisitinguser!== null

 if (existingUser !== null)