创建Node项目
并下载数据库依赖 npm install mysql2
-
目录结构:
-
dbconfig.js
数据库配置文件
//导入mysql模块
const mysql = require('mysql2');
//创建数据库连接对象
const connection = mysql.createConnection({
host:'localhost',
port:3306,
user:'root',
password:'*****',
database:'deyun'
})
//让数据库的连接对象对外可见
module.exports = connection;
- httpserver.js
//导入http模块:用户创建http服务器
const http = require('http');
//导入querystring模块:用来解析客户端提交的数据
const queryString = require('querystring');
//导入数据库的配置模块:用于数据库的操作
const connection = require('../db/dbconfig');
//创建http服务器:对应的请求地址是:http://localhost:3000/index
let server = http.createServer((req,res) => {
//获取客户端请求的地址
let clientUrl = req.url;
console.log(clientUrl);
if (clientUrl === '/index'){
let body = '';//用来保存客户端提交的请求数据
//给请求对象req绑定'data'事件:用来获取客户端的请求数据
req.on('data',chunk => {
body += chunk;
});
//给请求对象req绑定'end'事件
req.on('end',() => {
//将body中的数据转换为键值对的形式
let params = queryString.parse(body);
//设置服务器端的响应头信息
res.writeHead(200, {'Content-Type': 'text/plain;charset=utf-8'});
//拼接响应字符串
let res_str = '姓名:'+params.emp_name+"\n"+
'性别:'+params.emp_gender+"\n"+
'生日:'+params.emp_birthday+"\n"+
'电话:'+params.emp_phone+'\n'+
'地址:'+params.emp_address;
console.log(res_str);
//将响应字符串发送给客户端 先把信息写入数据库,再响应给客户端
save(params);
res.write(res_str);
//关闭连接
res.end();
})
}
}).listen(3000);//绑定端口号
//创建将数据保存到数据库的方法
function save(params){
connection.query('insert into employee set ?',{
name:params.emp_name,
gender:params.emp_gender,
birthday:params.emp_birthday,
phone:params.emp_phone,
address:params.emp_address
},(err,result) => {
if(err){
console.log(err);
return;
}
console.log('插入数据成功');
connection.end();//断开数据库的连接
})
}
- client.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="http://localhost:3000/index" method="post">
姓名:<input type="text" name="emp_name"><br><br>
性别:<input type="text" name="emp_gender"></input><br><br>
生日:<input type="date" name="emp_birthday"><br><br>
电话:<input type="text" name="emp_phone"><br><br>
地址:<input type="text" name="emp_address"><br><br>
<input type="submit" value="提交">
</form>
</body>
</html>
实现效果:
未使用ajax实现的弊端:
- 点击提交后页面会进行跳转 跳转到服务器发给客户端的响应
- 全局刷新