【问题标题】:Node.js & express cannot post / error with a simple Bootstrap formNode.js & express 无法使用简单的 Bootstrap 表单发布/错误
【发布时间】:2015-03-12 01:48:57
【问题描述】:

当我尝试登录/验证用户并导航到用户页面时,我的客户端浏览器中出现“无法发布 /”错误。在我开始使用 Bootstrap 之前,这曾经可以正常工作(即,它是一个简单的容器,没有表单中的类和其他样式元素)。

有趣的是,有时当我尝试在浏览器中逐步使用 WebKit 调试器(包括客户端和服务器端代码)时,它可以正常工作。但是当我尝试在调试器中没有断点的情况下正常登录时不起作用。

我在使用 Bootstrap 创建的 html 文件中有以下简单形式:

<div id="navbar" class="navbar-collapse collapse">
  <form class="navbar-form navbar-right" enctype="multipart/form-data" method="post" id="loginForm">
    <div class="form-group">
      <input type="text" placeholder="Email" class="form-control" id="userId" name="userId"/>
    </div>
    <div class="form-group">
      <input type="password" placeholder="Password" class="form-control" id="password" name="password"/>
    </div>
    <button class="btn btn-success" onclick="validateLoginForm()"/>Sign in</button>
    <div>
      <input type="checkbox" id="keeplogged" name="keeplogged" checked="checked"/>
      <label for="keeplogged"> Keep me logged in </label>
    </div>
 </form>
</div>

Javascript 代码是:

function validateLoginForm() {
   var ret = validateLoginData();
   if(ret) {
      loginUser("loginForm");
   }

   return ret;
}

function loginUser(formId) {
   var xhr = new XMLHttpRequest();
   xhr.withCredentials = true;
   xhr.onreadystatechange = function() {
      if(xhr.readyState == 4) {
         if(xhr.status == 200) {
            //navigate to the home page
            window.location = "/home.html";
         }
         else {
            console.log("Login problem with the client request.");
         }
      }
   };

   //Send form to server in background
   xhr.open("POST", "/login");
   xhr.send(new FormData(document.getElementById(formId)));
}

/login 的服务器路由如下所示:

   app.post("/login", function(req, res) {
      accountMgr.authenticateUser(req, res, function(err, user){
         if(user) {
            util.log("User <" + user.email + "> logged in successfully!");

            // Regenerate session when signing in to prevent fixation
            req.session.regenerate(function(){
               // Store the user's primary key in the session store to be retrieved,
               // or in this case the entire user object
               req.session.user = user;
               req.session.success = 'Authenticated as ' + user.name;
               if(req.body["keeplogged"] == "on"){
                  res.cookie('user', user.email, { maxAge: 3600000000 });
                  res.cookie('pass', req.body["password"], { maxAge: 3600000000 });
               }
               res.send('success', 200);
            });
         }
         else {
            util.log("User <" + req.body["userId"] + "> failed to login with error: " + err);
            req.session.error = 'Authentication failed, please check your '
                                      + ' username and password.';
            res.send(404);
         }
      });
   });

exports.createAccountManager = function(db, settings) {
   //Authenticate the user credentials
   this.authenticateUser = function (req, res, cb) {
      var userId = req.body["userId"],
          passwd = req.body["password"];

      util.log("Received authenticate request for user: " + userId);

      //first check if the user with the given id exists or not
      db.users.findOne({email: userId}, function(err, user) {
        //now check if the password entered by the user matches with our DB record
        //note: new users will not have the salt value too!
        if(user != null && user.salt != null) {
           if(user.active) {
              hash(passwd, user.salt, function(err, hashKey){
                 if (err) return cb(err);
                 if (hashKey == user.hashKey) return cb(null, user);
                 cb(new Error('Invalid password'));
              });
           }
           else {
              util.log("User with id: " + userId + " is not confirmed!");
              cb(new Error('User account not confirmed'));
           }
        }
        else {
           util.log("Cannot find user with id: " + userId);
           cb(new Error('Invalid user id'));
        }
      });
   };
};

关于我为什么会收到此错误的任何想法?以及如何解决?

编辑: 这是完美运行的旧形式(没有 Bootstrap):

 <div id="loginContainer">
     <form enctype="multipart/form-data" method="post" id="loginForm">
    <div id="loginHeader">
        <h2>Log In</h2>
    </div>

    <br>
    <div id="loginContent">
                <div>
                    Email <input type="email" id="userId" name="userId" class="dlgText" value="" autocomplete="on" />
                </div>
                <br>
                <div>
                    Password <input type="password" id="password" name="password" class="dlgText" value="" autocomplete="on" />
                </div>
                <br>
                <div>
                    <input type="checkbox" id="keeplogged" name="keeplogged" checked="checked"/>
                    <label for="keeplogged"> Keep me logged in </label>
                </div>
    </div>

            <br>
    <div id="loginFooter">
                <div>
        <input type="button" id="ok" name="ok" class="dlgButton" value="Log In" onclick="validateLoginForm()"/>
        <input type="button" id="cancel" name="cancel" class="dlgButton" value="Cancel" onclick="cancelLoginUI()"/>
                </div>

        <div align=right><a href="javascript:forgotPassword()">Forgot Password?</a></div>
    </div>
    <div class="clear"></div>
     </form>
 </div>

【问题讨论】:

    标签: javascript html css node.js twitter-bootstrap


    【解决方案1】:

    首先,Node.js 应用程序是否托管在发出请求的同一台服务器上 - 如果不是,您可能会发现跨域请求存在问题。

    您也是exporting 服务器文件中的应用程序对象吗?看起来你有一个exports.createAccountManager 函数。因为我猜你不在 Express 初始化的主 app.js 文件的上下文中,你可能需要将定义传递回调用模块。

    我很感兴趣你说它有时有效。当你说工作时,你的意思是它完全按照你的预期工作还是没有返回错误?

    【讨论】:

    • 该帐户管理代码是一个单独的文件 (accountManager.js),它导出方法:authenticateUser()。所有代码都可以与旧 UI(没有 Bootstrap)完美配合,我将添加到原始帖子中。
    • 这个新代码(使用 Bootstrap)有时会在我在登录客户端代码中设置断点后单步执行调试器时工作。但是当我单步执行服务器代码时,它仍然在客户端失败并出现该错误。但是我看到服务器代码总是被执行,并且我在日志文件中看到用户登录成功消息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 2011-11-23
    • 1970-01-01
    • 2019-02-19
    • 1970-01-01
    相关资源
    最近更新 更多