当前位置:网站首页>Nodejs + Mysql realize simple registration function (small demo)
Nodejs + Mysql realize simple registration function (small demo)
2022-04-23 13:06:00 【It's never too late to be alone】
- Create a database and create data tables , Pictured :

2. Create two fields ,uuid Field is used to receive passwords ,userName Field is used to receive the name , Pictured :

3.nodejs The code is as follows , After operation :
// Express It's a simple and flexible one node.js Web Application framework , Provides a series of powerful features to help you create a variety of Web application , And the rich HTTP Tools .
var express = require('express');
var mysql = require('mysql');
var app = express();
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });// establish application/x-www-form-urlencoded Code parsing
// Configure and modify the database user name 、 And password and database name
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'root',
port: '3306',
database: 'expressdb'
});
connection.connect();
// Solve cross domain access
app.all('/',function(req,res,next){
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');
next();
});
app.post('/',urlencodedParser,function(req,res){
// console.log(req);
var name = req.body.name;
var password = req.body.password;
var data = [password,name];
var _res = res;
var sql_add = 'INSERT INTO user(uuid,userName) VALUES(?,?)';// Add data
var sql_select = 'SELECT * FROM user';// Query data
connection.query(sql_select,function(err,result){
if(err){
_res.send(err.message);
return;
}else{
var ta = true;
result.forEach(item => {
if(item.uuid == password && item.userName == name){
_res.send(' Your account has been registered , Clear re registration !');
ta = false;
return;
}
});
if(ta){
connection.query(sql_add,data,function(err,result){
if(err){
_res.send(err.message);
return;
}
_res.send(' Registered successfully ;');
})
}
}
})
// res.end(' The request is successful ');
});
var server = app.listen(3000,function(){
var host = server.address().address
var port = server.address().port
console.log(' Successfully monitored ',host,port);
});
4. The front-end request code is as follows :
<body>
<ul>
<li class="list">
<span class="name"> full name :</span>
<input type="" name="name" id="name" value="" />
</li>
<li class="list">
<span class="password"> password :</span>
<input type="" name="password" id="password" value="" />
</li>
<button class="but" onclick="register()"> register </button>
</ul>
</body>
<script type="text/javascript">
function register() {
var name = $('#name').val();
var passwords = $('#password').val();
ajax(name,passwords);
}
function ajax(name,passwords) {
$.ajax({
async: true, // Boolean value , Indicates whether the request is processed asynchronously . The default is true.
url: "http://127.0.0.1:3000/", // Specify the time to send the request URL
type: "post",
data: {
'name':name,
'password': passwords
}, // Requested data , Data passed to the background
success: function(backdata) {
// After the request is successful, the returned data will be encapsulated in the first parameter of the callback function
// adopt backdata To get the required data
console.log(backdata)
},
error: function(err) {
// The function returned when the response is unsuccessful
console.log(err);
console.log(' request was aborted ');
},
dataType: 'text' // Set the returned data type
})
}
</script>
5. Click registration , After successful registration, as shown in the figure :

6. Database added successfully

7. Add the same data again

notes : The logic layer side must be clear , Otherwise it will be reported Error 1: Cannot set headers after they are sent to the client:
reason : The client makes a request , The server gives two or more responses
Solution : Clean up the excess number of responses ; Immediately after each response return Drop function
版权声明
本文为[It's never too late to be alone]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231303465650.html
边栏推荐
- AUTOSAR from introduction to mastery 100 lectures (52) - diagnosis and communication management function unit
- 4.22学习记录(你一天只做了水题是吗)
- CMSIS cm3 source code annotation
- 「玩转Lighthouse」轻量应用服务器自建DNS解析服务器
- V-model binding value in El select, data echo only displays value, not label
- Free and open source agricultural Internet of things cloud platform (version: 3.0.1)
- Golang implements a five insurance and one gold calculator with web interface
- 产品开发都应该知道的8个网站,增强工作体验
- 4.22 study record (you only did water problems in one day, didn't you)
- 51 single chip microcomputer stepping motor control system based on LabVIEW upper computer (upper computer code + lower computer source code + ad schematic + 51 complete development environment)
猜你喜欢

Wonderful review | the sixth issue of "source" - open source economy and industrial investment

【微信小程序】flex布局使用记录

The accuracy and speed are perfectly balanced, and the latest image segmentation SOTA model is released!!!

Servlet监听器&过滤器介绍

100 GIS practical application cases (51) - a method for calculating the hourly spatial average of NC files according to the specified range in ArcGIS

MySQL supports IP access

filter()遍历Array异常友好

The El table horizontal scroll bar is fixed at the bottom of the visual window

51 single chip microcomputer stepping motor control system based on LabVIEW upper computer (upper computer code + lower computer source code + ad schematic + 51 complete development environment)

Design of STM32 multi-channel temperature measurement wireless transmission alarm system (industrial timing temperature measurement / engine room temperature timing detection, etc.)
随机推荐
8086 of x86 architecture
7_Addmodule和基因加和法add 得到的细胞类型打分在空间上空转对比
filter()遍历Array异常友好
Kernel error: no rule to make target 'Debian / canonical certs pem‘, needed by ‘certs/x509_ certificate_ list‘
(1) Openjuterpyrab comparison scheme
Byte jump 2020 autumn recruitment programming question: quickly find your own ranking according to the job number
4.22 study record (you only did water problems in one day, didn't you)
Translation of multi modal visual tracking: review and empirical comparison
Go language: passing slices between functions
Record Alibaba cloud server mining program processing
Hanlp word splitter (via spark)
CVPR 2022 & ntire 2022 | the first transformer for hyperspectral image reconstruction
22. 括号生成
初鉴canvas,展示个小小的小案例
There is no need to crack the markdown editing tool typora
Servlet监听器&过滤器介绍
【微信小程序】flex布局使用记录
STM32 is connected to the motor drive, the DuPont line supplies power, and then the back burning problem
Learning materials
FFmpeg常用命令