当前位置:网站首页>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
边栏推荐
- Free and open source intelligent charging pile SaaS cloud platform of Internet of things
- Record a website for querying compatibility, string Replaceall() compatibility error
- decast id.var measure. Var data splitting and merging
- Temperature and humidity monitoring + timing alarm system based on 51 single chip microcomputer (C51 source code)
- The project file '' has been renamed or is no longer in the solution, and the source control provider associated with the solution could not be found - two engineering problems
- 数据库中的日期时间类型
- Process virtual address space partition
- CMSIS cm3 source code annotation
- AUTOSAR from introduction to mastery 100 lectures (50) - AUTOSAR memory management series - ECU abstraction layer and MCAL layer
- Introduction to servlet listener & filter
猜你喜欢
AUTOSAR from introduction to mastery 100 lectures (52) - diagnosis and communication management function unit
The accuracy and speed are perfectly balanced, and the latest image segmentation SOTA model is released!!!
CVPR 2022 & ntire 2022 | the first transformer for hyperspectral image reconstruction
初鉴canvas,展示个小小的小案例
R语言中dcast 和 melt的使用 简单易懂
Design of body fat detection system based on 51 single chip microcomputer (51 + OLED + hx711 + US100)
软件测试周刊(第68期):解决棘手问题的最上乘方法是:静观其变,顺水推舟。
世界读书日:我想推荐这几本书
MySQL supports IP access
mysql支持ip访问
随机推荐
AUTOSAR from introduction to mastery 100 lectures (50) - AUTOSAR memory management series - ECU abstraction layer and MCAL layer
Golang implements MD5, sha256 and bcrypt encryption
Go language array operation
Process virtual address space partition
Record Alibaba cloud server mining program processing
mysql 基本语句查询
CGC: contractual graph clustering for community detection and tracking
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?
GIS practical tips (III) - how to add legend in CASS?
Free and open source agricultural Internet of things cloud platform (version: 3.0.1)
AUTOSAR from introduction to mastery 100 lectures (83) - bootloader self refresh
100 GIS practical application cases (51) - a method for calculating the hourly spatial average of NC files according to the specified range in ArcGIS
安装nngraph
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)
nodejs + mysql 实现简单注册功能(小demo)
AUTOSAR from introduction to mastery 100 lectures (87) - key weapon of advanced EEA - AUTOSAR and DDS
21 days learning mongodb notes
The quill editor image zooms, multiple rich text boxes are used on one page, and the quill editor upload image address is the server address
Navicat远程连接数据库 出现 1130- Host xxx is not allowed to connect to this MySQL server错误
教你快速开发一个 狼人杀微信小程序(附源码)