当前位置:网站首页>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
边栏推荐
- Teach you to quickly develop a werewolf killing wechat applet (with source code)
- Get the punch in record of nailing attendance machine
- 100 GIS practical application cases (52) - how to keep the number of rows and columns consistent and aligned when cutting grids with grids in ArcGIS?
- Huawei cloud MVP email
- mui 关闭其他页面,只保留首页面
- The accuracy and speed are perfectly balanced, and the latest image segmentation SOTA model is released!!!
- 初鉴canvas,展示个小小的小案例
- Go language slicing operation
- FFmpeg常用命令
- World Book Day: I'd like to recommend these books
猜你喜欢

three. JS text ambiguity problem

Customize the shortcut options in El date picker, and dynamically set the disabled date

If you were a golang interviewer, what questions would you ask?

Read the data in Presto through sparksql and save it to Clickhouse

jmeter操作redis

5 free audio material websites, recommended collection

世界读书日:我想推荐这几本书

World Book Day: I'd like to recommend these books

CVPR 2022 & ntire 2022 | the first transformer for hyperspectral image reconstruction

Kernel error: no rule to make target 'Debian / canonical certs pem‘, needed by ‘certs/x509_ certificate_ list‘
随机推荐
Use of Presto date function
AUTOSAR from introduction to mastery 100 lectures (87) - key weapon of advanced EEA - AUTOSAR and DDS
基于uniapp异步封装接口请求简介
AUTOSAR from introduction to mastery 100 lectures (81) - FIM of AUTOSAR Foundation
AUTOSAR from introduction to mastery 100 lectures (83) - bootloader self refresh
mui + hbuilder + h5api模拟弹出支付样式
100 lectures on practical application cases of Excel (VIII) - report connection function of Excel
Complete project data of UAV apriltag dynamic tracking landing based on openmv (LabVIEW + openmv + apriltag + punctual atom four axes)
HQL statement tuning
STM32 tracking based on open MV
These vscode extensions are my favorite
Melt reshape decast long data short data length conversion data cleaning row column conversion
AUTOSAR from introduction to mastery lecture 100 (84) - Summary of UDS time parameters
Go language mapping operation
Design of body fat detection system based on 51 single chip microcomputer (51 + OLED + hx711 + US100)
mui 关闭其他页面,只保留首页面
Byte warehouse intern interview SQL questions
AUTOSAR from introduction to mastery 100 lectures (52) - diagnosis and communication management function unit
After the data of El table is updated, the data in the page is not updated this$ Forceupdate() has no effect
Free and open source agricultural Internet of things cloud platform (version: 3.0.1)