Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/446.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从.js文件中的EJS文件获取表单输入_Javascript_Node.js_Firebase_Firebase Authentication - Fatal编程技术网

Javascript 从.js文件中的EJS文件获取表单输入

Javascript 从.js文件中的EJS文件获取表单输入,javascript,node.js,firebase,firebase-authentication,Javascript,Node.js,Firebase,Firebase Authentication,我不熟悉Javscript编程和使用NodeJs。我正在尝试使用NodeJS和Express创建登录/注册页面,以验证Firebase后端在登录和注册页面上提交的用户信息 用户在register.ejs文件中构造的表单上输入信息。例如,我使用document.getElementByID获取用户的输入并将其存储在变量(txtmail/txtPassword)中。我使用EventListener等待用户在btnRegister上提交表单,并将txtmail和txtPassword的内容传递到变量p

我不熟悉Javscript编程和使用NodeJs。我正在尝试使用NodeJS和Express创建登录/注册页面,以验证Firebase后端在登录和注册页面上提交的用户信息

用户在register.ejs文件中构造的表单上输入信息。例如,我使用document.getElementByID获取用户的输入并将其存储在变量(txtmail/txtPassword)中。我使用EventListener等待用户在btnRegister上提交表单,并将txtmail和txtPassword的内容传递到变量password和email中,然后将变量password和email传递到auth.createUserWithEmailAndPassword中,以在Firebase后端创建用户

我在将注册页面上的用户输入传递到btnRegister时遇到问题。特别是,我收到以下关于txtmail、txtPassword的错误消息:

register.ejs:
登记
名称
电子邮件
密码
确认密码
登记

有账户吗

users.js: const express=require('express'); const router=express.router(); const bcrypt=require('bcryptjs'); //获取元素 const txtEmail=document.getElementById('email'); const txtPassword=document.getElementById('password'); const btnRegister=document.getElementById('btnRegister'); //用户模型 const User=require(“../models/User”) //登录页面 router.get('/login',(req,res)=>res.render('login'); //注册页 router.get('/register',(req,res)=>res.render('register'); //登记册 路由器.post('/register',(req,res)=>{ const{name,email,password2}=req.body; const promise=(电子邮件、密码、密码2); 让错误=[]; 如果(!name | | |!email | |!password | |!password2){ 错误。推送({msg:'请输入所有字段'}); } 如果(密码!=密码2){ 错误。推送({msg:'密码不匹配'}); } 如果(密码长度<6){ 错误。推送({msg:'密码必须至少为6个字符'); } 如果(errors.length>0){ res.render('寄存器'{ 错误, 名称 电子邮件, 密码, 密码2 }); }否则 { btnRegister.attachEvent('onclick',e=>{ const email=txtEmail.value; const password=txtPassword.value; const auth=firebase.auth(); const promise=auth.createUserWithEmailAndPassword(电子邮件,密码); promise.catch(e=>console.log(e.message)); }); } }); module.exports=路由器; app.js const express=require('express'); const expressLayouts=require('express-ejs-layouts'); //const mongoose=require('mongoose'); const firebase=require('firebase'); 常量app=express(); //数据库配置 //const db=require('./config/keys')。MongoURI; //连接到Mongo //connect(db,{useNewUrlParser:true}) .然后(()=>console.log('MongooseDB Connected…')) .catch(err=>console.log(err)); //火基配置 变量配置={ apiKey:“********” authDomain:“*******”, 数据库URL:“*******”, projectId:“*******”, storageBucket:“*******, messagingSenderId:“*******”, appId:“*******” }; //连接到Firebase firebase.initializeApp(配置); //EJS 应用程序使用(expressLayouts); 应用程序集(“查看引擎”、“ejs”); //体分析器 use(express.urlencoded({extended:true})); //路线 app.use('/',require('./routes/index.js'); app.use('/users',require('/routes/users.js'); const PORT=process.env.PORT | 5000; app.listen(PORT,console.log(`Server start on PORT${PORT}`)); layout.ejs 试验
用户将其信息提交到注册表中,信息存储到变量中,并基于Firebase身份验证创建用户

const txtEmail = document.getElementById('email');
                       ^

ReferenceError: document is not defined
register.ejs:

<div class="row mt-5">
        <div class="col-md-6 m-auto">
          <div class="card card-body">
            <h1 class="text-center mb-3">
              <i class="fas fa-user-plus"></i> Register
            </h1>
            <% include ./partials/messages %>
            <form action="/users/register" method="POST">
              <div class="form-group">
                <label for="name">Name</label>
                <input
                  type="name"
                  id="name"
                  name="name"
                  class="form-control"
                  placeholder="Enter Name"
                  value="<%= typeof name != 'undefined' ? name : '' %>"
                />
              </div>
              <div class="form-group">
                <label for="email">Email</label>
                <input
                  type="email"
                  id="email"
                  name="email"
                  class="form-control"
                  placeholder="Enter Email"
                  value="<%= typeof email != 'undefined' ? email : '' %>"
                />
              </div>
              <div class="form-group">
                <label for="password">Password</label>
                <input
                  type="password"
                  id="password"
                  name="password"
                  class="form-control"
                  placeholder="Create Password"
                  value="<%= typeof password != 'undefined' ? password : '' %>"
                />
              </div>
              <div class="form-group">
                <label for="password2">Confirm Password</label>
                <input
                  type="password"
                  id="password2"
                  name="password2"
                  class="form-control"
                  placeholder="Confirm Password"
                  value="<%= typeof password2 != 'undefined' ? password2 : '' %>"
                />
              </div>
              <button id="btnRegister" type="submit" class="btn btn-primary btn-block">
                Register
              </button>
            </form>
            <p class="lead mt-4">Have An Account? <a href="/users/login">Login</a></p>
          </div>
        </div>

<script src="/routes/users.js"></script>

users.js:

const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');


  //Get Elements
  const txtEmail = document.getElementById('email');
  const txtPassword = document.getElementById('password');
  const btnRegister = document.getElementById('btnRegister');

//User model
const User = require('../models/user')

//Login page
router.get('/login', (req, res) => res.render('login'));

//Register page
router.get('/register', (req, res) => res.render('register'));

// Register
router.post('/register', (req, res) => {
    const { name, email, password, password2 } = req.body;
    const promise = (email, password, password2);
    let errors = [];

    if (!name || !email || !password || !password2) {
      errors.push({ msg: 'Please enter all fields' });
    }

    if (password != password2) {
      errors.push({ msg: 'Passwords do not match' });
    }

    if (password.length < 6) {
      errors.push({ msg: 'Password must be at least 6 characters' });
    }

    if (errors.length > 0) {
      res.render('register', {
        errors,
        name,
        email,
        password,
        password2
      });
    } else 
        {
          btnRegister.attachEvent('onclick', e => {
            const email = txtEmail.value;
            const password = txtPassword.value;
            const auth = firebase.auth();
            const promise = auth.createUserWithEmailAndPassword(email, password);
            promise.catch(e => console.log(e.message));
          });

        }
});


module.exports = router;


app.js 

const express = require('express');
const expressLayouts = require('express-ejs-layouts');
//const mongoose = require('mongoose');
const firebase = require('firebase');

const app = express();

//DB config
//const db = require('./config/keys').MongoURI;

//Connect to Mongo
//mongoose.connect(db, { useNewUrlParser: true})
    .then(() => console.log('MongooseDB Connected...'))
    .catch(err => console.log(err));

//Firebase config
var config = {
        apiKey: "********"
        authDomain: "*****",
        databaseURL: "*****",
        projectId: "*****",
        storageBucket: "******,
        messagingSenderId: "******",
        appId: "*******"
};
//Connect to Firebase
firebase.initializeApp(config);

//EJS
app.use(expressLayouts);
app.set('view engine', 'ejs');

//Bodyparser
app.use(express.urlencoded({ extended: true }));

//Routes
app.use('/', require('./routes/index.js'));
app.use('/users', require('./routes/users.js'));

const PORT = process.env.PORT || 5000;

app.listen(PORT, console.log(`Server started on port ${PORT}`));

layout.ejs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel='stylesheet' href="https://bootswatch.com/4/materia/bootstrap.min.css">
    <script src="https://kit.fontawesome.com/420440220d.js"></script>
    <script src="/__/firebase/6.3.4/firebase-app.js"></script>
    <script src="/__/firebase/6.3.4/firebase-auth.js"></script>
    <script src="/__/firebase/6.3.4/firebase-firestore.js"></script>
    <script src="/routes/users.js"></script>
</body>

    <title>Test</title>
</head>
<body>

    <div class="container">
        <%- body %>
    </div>

    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

</body>
</html>