在EJS中单击提交按钮时无法提交表单

时间:2013-11-20 14:14:14

标签: javascript forms node.js express ejs

大家好我遇到了一个问题,我不明白为什么,这很奇怪,或者我错误地编写代码,所以我希望你们能指出错误或启发我。

所以我试图将表单提交到我的数据库,在提交表单之前,验证函数将验证数据,如果有错误则会通知用户

当我点击提交按钮时,表单无法提交且没有任何反应,终端没有错误,控制台没有错误,没有任何内容(看起来你点击了表单内的<button>,而表单正在等待{ {1}}提交表单&gt;

这是完整的代码https://github.com/johnlim5847/form-test

App.js (我认为这里没有错)

<input type="submit">

路由/ index.js

  var express = require('express'),
         app = express(),
       http = require('http'),
       path = require('path'),
       MongoClient = require('mongodb').MongoClient,
       routes = require('./routes'),
       passport = require('passport');
    MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
        "use strict";
        if(err) throw err;
    // all environments
    app.set('port', process.env.PORT || 3000);
    app.set('views', __dirname + '/public/views');
    app.set('view engine', 'ejs');
    app.use('/static', express.static(path.join(__dirname, 'public')));
    app.use(express.cookieParser());
    app.use(express.favicon());
    app.use(express.logger('dev'));
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(express.session({ secret: 'Super Duper Awesome Duck' }));
    app.use(passport.initialize());
    app.use(passport.session());
    app.use(app.router);
    // development only
    if ('development' == app.get('env')) {
      app.use(express.errorHandler());
    }

    routes(app, db);

    http.createServer(app).listen(app.get('port'), function(){
      console.log('Express server listening on port ' + app.get('port'));
    });

    });

路由/ session.js

var SessionHandler = require('./session');

module.exports = exports = function(app, db) {
var sessionHandler = new SessionHandler(db);
app.use(sessionHandler.isLoggedInMiddleware);
// Signup form
app.post('/register', sessionHandler.handleSignup);

app.use(function (req,res) {
 res.status(404).render('error', {
 url: req.originalUrl
  });
});

app.get('*',function(req, res){
  res.render('master', { title: 'form' });
});


}

register.ejs

var UsersDAO = require('../users').UsersDAO
  , SessionsDAO = require('../sessions').SessionsDAO;

/* The SessionHandler must be constructed with a connected db */
function SessionHandler (db) {
    "use strict";

    var users = new UsersDAO(db);
    var sessions = new SessionsDAO(db);



   function validateSignup(publicUsername, password, confirmPassword, email, confirmEmail, errors) {
        "use strict";
        var USER_RE = /^[a-zA-Z0-9_-]{2,25}$/;
        var PASS_RE = /^.{6,100}$/;
        var EMAIL_RE = /^[\S]+@[\S]+\.[\S]+$/;

        errors['publicUsername_error'] = "";
        errors['password_error'] = "";
        errors['confirmPassword_error'] = "";
        errors['email_error'] = "";
        errors['confirmEmail_error'] = "";

        if (!USER_RE.test(publicUsername)) {
            errors['publicUsername_error'] = "Try just letters and numbers, e.g: Ed, 69, Kelvin and etc";
            return false;
        }
        if (!PASS_RE.test(password)) {
            errors['password_error'] = "Password must be at least 6 characters long";
            return false;
        }
        if (password != confirmPassword) {
            errors['confirmPassword_error'] = "Password must match";
            return false;
        }
        if (!EMAIL_RE.test(email)) {
                errors['email_error'] = "Invalid email address";
                return false;
            }
         if (email != confirmEmail) {
            errors['confirmEmail_error'] = "Email must match";
            return false;
        }
        return true;
    }

    this.handleSignup = function(req, res, next) {
        "use strict";

        var email = req.body.email,
         confirmEmail = req.body.confirmEmail,
         password = req.body.password,
         confirmPassword = req.body.confirmPassword,
         firstName = req.body.firstName,
         lastName = req.body.lastName,
         penName = req.body.penName,
         publicUsername = req.body.publicUsername;

        // set these up in case we have an error case
        var errors = {'email': email,'publicUsername': publicUsername,'firstName': firstName,'lastName': lastName,'penName': penName}
        if (validateSignup(publicUsername, password, confirmPassword, email, confirmEmail, errors)) {
            users.addUser(email, password, firstName, lastName, penName, publicUsername, function(err, user) {
                "use strict";

                if (err) {
                    // this was a duplicate
                    if (err.code == '11000') {
                        errors['email_error'] = "Email already in use. Please choose another";
                        return res.render("register", errors);
                    }
                    // this was a different error
                    else {
                        return next(err);
                    }
                }

                sessions.startSession(user['_id'], function(err, session_id) {
                    "use strict";

                    if (err) return next(err);

                    res.cookie('session', session_id);
                    return res.redirect('/');
                });
            });
        } else {
            console.log("user did not validate");
            return res.render("register", errors);
        }
    }
}

我认为这可能是一个愚蠢的错误,我希望我的HTML标签LOL没有任何问题

3 个答案:

答案 0 :(得分:0)

我认为您需要一个空格,以便type='submit'class变为:type='submit' class

答案 1 :(得分:0)

好的,所以经过简短的调试会话后:

取自Angular的docs

  

由于表单在客户端Angular应用程序中的作用是   与经典的往返应用程序不同,它是理想的   浏览器不将表单提交翻译成整页重新加载   将数据发送到服务器。而是一些javascript逻辑   应该触发处理表单提交   特定于应用的方式。

     

出于这个原因,Angular会阻止默认操作(表单提交   除非元素具有action属性,否则到服务器)   指定。

因此您似乎没有为表单提交提供正确的处理: - )

所以要么提供一个,要么将'action'属性添加到表单中 - 应该“修复”它

如果这对您有意义,请告诉我。

答案 2 :(得分:-1)

您缺少 register.ejs

form 标记内的 action 属性

应该如下

R.zipWith

现在,点击“提交” 时,将生成 POST 请求,服务器应查找中提到的 post 类型的路由>动作


代码的另一件事是...您需要使用“ exports” 关键字声明 SessionHandler 函数,如下所述。

<form method="post" action="/user/register" class="pure-form pure-form-aligned">

OR

exports.SessionHandler = async (req, res, next) => {
  // Session handler with arrow function
}