search
HomeWeb Front-endJS TutorialHow to implement the login and registration function using node.js and other technologies?

This article mainly introduces node.js express mySQL ejs bootstrop to implement the website login and registration function. It is very good and has reference value. Friends in need can refer to it

Comrades, after unremitting efforts, After checking various documents, I finally came up with a slightly decent node project. Of course, if you use it directly in the project, this demo is too simple. After all, a complete login registration has a lot of practical content. In this case, mySQL In the user list, for ease of understanding, only two fields, username and password, are set. For normal login and registration, there will definitely be more fields. But for those who are new to node, such as the author, I still learned a lot. Even nervously, I didn’t know what to write as follows. I must have made reference to many other teenagers’ blogs on the Internet. In the future, the login and registration demo will be based on the needs of the project. Improved,

The effect is as follows

How to implement the login and registration function using node.js and other technologies?

Effect.gif

Project structure

Main entrance app.js

app.js is the main entrance to the program. It is generally used to write the middleware and various settings we introduce.

var express = require('express');
// NodeJS中的Path对象,用于处理目录的对象,提高开发效率
var path = require('path');
// 用来定义网页logo的中间件
var favicon = require('serve-favicon');
// NodeJs中Express框架使用morgan中间件记录日志
// Express中的app.js文件已经默认引入了该中间件var logger = require('morgan');
// 使用app.use(logger('dev'));以将请求信息打印在控制台,便于开发调试,
// 但实际生产环境中,需要将日志记录在log文件里
var logger = require('morgan');
// 存储登录信息中间件
var cookieParser = require('cookie-parser');
// 解析请求体的中间件
var bodyParser = require('body-parser');
// 引入模块的js文件
var routes = require('./routes/index');
// var users = require('./routes/user');
// 引入session中间件
var session=require('express-session');
// 创建项目示例
var app = express();
// 引入我们需要的模板
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// 用摩记录请求
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// 利用cookieParser中间件存取信息
app.use(cookieParser("Luck"));
// 利用session中间件存取信息
app.use(session({
  secret:'luck',
  resave:false,
  saveUninitialized:true
}));
// 静态化我们的public文件下的文件,使其可以直接引用
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
// app.use('/users', users);
// 捕捉404状态
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});
module.exports = app;
app.listen(3000,'127.0.0.1')
routes下的index.js文件
index.js这里我用来处理页面的路由跳转
var express = require('express');
var router = express.Router();
// 为数据库链接的js文件,可查询数据库中的用户名和密码等信息
var usr=require('netRequest/dbConnect');
// 获取首页登录信息
router.get('/', function(req, res) {
  if(req.cookies.islogin){
    req.session.islogin=req.cookies.islogin;
  }
  if(req.session.islogin){
    res.locals.islogin=req.session.islogin;
  }
 res.render('index', { title: 'HOME',test:res.locals.islogin});
});
// 登录页处理
router.route('/login')
  // get请求渲染页面  
  .get(function(req, res) {
    if(req.session.islogin){
      res.locals.islogin=req.session.islogin;
    }
    if(req.cookies.islogin){
      req.session.islogin=req.cookies.islogin;
    }
    res.render('login', { title: '用户登录' ,test:res.locals.islogin});
  })
  // post请求查询用户信息
  .post(function(req, res) {
    client=usr.connect();
    result=null;
    // 调用数据库方法
    usr.selectFun(client, req.body.username, function (result) {
      if(result[0]===undefined){
        res.send('没有该用户');
      }else{
        if(result[0].password==req.body.password){
          req.session.islogin=req.body.username;
          res.locals.islogin=req.session.islogin;
          res.cookie('islogin',res.locals.islogin,{maxAge:60000});
          res.redirect('/home');
        }else{
          res.redirect('/login');
        }
      }
    });
  });
// 退出登录页处理
router.get('/logout', function(req, res) {
  res.clearCookie('islogin');
  req.session.destroy();
  res.redirect('/');
});
// home页处理
router.get('/home', function(req, res) {
  if(req.session.islogin){
    res.locals.islogin=req.session.islogin;
  }
  if(req.cookies.islogin){
    req.session.islogin=req.cookies.islogin;
  }
  res.render('home', { title: 'Home', user: res.locals.islogin });
});
// 注册页处理
router.route('/reg')
  // get请求渲染页面
  .get(function(req,res){
    res.render('reg',{title:'注册'});
  })
  // post请求注册用户
  .post(function(req,res) {
    client = usr.connect();
    // 调用数据库方法
    usr.insertFun(client,req.body.username ,req.body.password2, function (err) {
       if(err) throw err;
       res.send('注册成功');
    });
  });
module.exports = router;
node_modules中netRequest/dbConnect.js

dbConnect.js

var mysql=require('mysql');
// 现在只是练习可以直接为数据库创建链接,
// 用户多时需要创建连接池
function connectServer(){
  var client=mysql.createConnection({
    host:'172.16.20.103',
    port:3308,
    database:'test',
    user:'JRJ_Win',
    password:'FT%^$fjYR56'
  })
  return client;
}
function selectFun(client,username,callback){
  client.query('select password from win.luck_user where username="'+username+'"',function(err,results,fields){
    if(err) throw err;
    callback(results);
  });
}
function insertFun(client , username , password,callback){
  client.query('insert into win.luck_user value(?,?)', [username, password], function(err,result){
    if( err ){
      console.log( "error:" + err.message);
      return err;
    }
     callback(err);
  });
}
exports.connect = connectServer;
exports.selectFun = selectFun;
exports.insertFun = insertFun;

The rest is the page template

login.ejs

<%- include header %>
<p class="container">
  <form class="col-sm-offset-4 col-sm-4 form-horizontal" role="form" method="post">
    <fieldset>
      <% if(locals.islogin) { %>
          <h3 id="用户-nbsp-nbsp-test-nbsp-nbsp-nbsp-已经登陆-br">用户: <%= test %>  已经登陆。<br></h3>
          <a class="btn" href="/logout" rel="external nofollow" > 退出登录 </a>
         <% } else{ %>
            <p class="form-group">
              <label class="col-sm-3 control-label" for="username">用户名</label>
              <p class="col-sm-9">
                <input type="text" class="form-control" id="username" name="username" placeholder="用户名" required>
              </p>
            </p>
            <p class="form-group">
              <label class="col-sm-3 control-label" for="password">密码</label>
              <p class="col-sm-9">
                <input type="password" class="form-control" id="password" name="password" placeholder="密码" required>
              </p>
            </p>
            <p class="form-group">
              <p class="col-sm-offset-3 col-sm-9">
                <button type="submit" class="btn btn-primary">登录</button>
              </p>
            </p>
      <% } %>
    </fieldset>
  </form>
</p>
<%- include footer %>

index.ejs

<%- include header %>
<p class="jumbotron text-center">
  <% if(locals.islogin){%>
    <h2 id="用户-nbsp-test-nbsp-nbsp">用户:<%= test %> </h2>已经登陆
    <% }else{%>
      <h2 id="a-nbsp-href-login-nbsp-rel-external-nbsp-nofollow-nbsp-rel-external-nbsp-nofollow-nbsp-请登录后查看-a"><a href="/login" rel="external nofollow" rel="external nofollow" >请登录后查看</a></h2>
  <%}%>  
</p>
<%- include footer %>

reg .ejs

<%- include header %>
<p class="container">
  <form class=" col-sm-offset-4 col-sm-4 form-horizontal" role="form" method="post">
    <fieldset>
      <p class="form-group">
        <label class="col-sm-3 control-label" for="username">用户名</label>
        <p class="col-sm-9">
          <input type="text" class="form-control" id="username" name="username" placeholder="用户名" required>
        </p>
      </p>
      <p class="form-group">
        <label class="col-sm-3 control-label" for="password2">密码</label>
        <p class="col-sm-9">
          <input type="password" class="form-control" id="password2" name="password2" placeholder="密码" required>
        </p>
      </p>
      <p class="form-group">
        <p class="col-sm-offset-3 col-sm-9">
          <button type="submit" class="btn btn-primary">注册</button>
        </p>
      </p>
    </fieldset>
  </form>
</p>
<%- include footer %>

header.ejs

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8"/>
  <title>Test</title>
  <link rel="stylesheet" href="/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="external nofollow" >
  <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
  <script type="text/javascript" src="/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>
<!--  <header>
    <h1><%= title %></h1>
  </header> -->
  <nav class="navbar navbar-default">
    <p class="container-fluid">
      <p class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Project name</a>
      </p>
      <p id="navbar" class="navbar-collapse collapse">
        <ul class="nav navbar-nav">
          <li class="active"><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >待定</a></li>
          <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >待定</a></li>
          <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >待定</a></li>
          <li class="dropdown">
            <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">待定<span class="caret"></span></a>
            <ul class="dropdown-menu">
              <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Action</a></li>
              <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Another action</a></li>
              <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Something else here</a></li>
              <li role="separator" class="pider"></li>
              <li class="dropdown-header">Nav header</li>
              <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Separated link</a></li>
              <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >One more separated link</a></li>
            </ul>
          </li>
        </ul>
        <ul class="nav navbar-nav navbar-right">
          <li class="active"><a title="主页" href="/" rel="external nofollow" >首页<span class="sr-only">(current)</span></a></li>
          <li><a title="登陆" href="/login" rel="external nofollow" rel="external nofollow" >登录</a></li>
          <li><a title="注册" href="/reg" rel="external nofollow" >注册</a></li>
        </ul>
      </p>
    </nav>
    <article>

footer.ejs

</article>
</body>
</html>

The main code of the project is here. If you want to understand it, it will probably take a while.

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to fix the header and first column in Vue

How to use the image annotation component in jquery.picsign

How to package the koa2 framework app through webpack? What should I do?

Detailed interpretation of Vue component development ideas

Detailed interpretation of how to use components and their functions in Vue.js?

The above is the detailed content of How to implement the login and registration function using node.js and other technologies?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment