简单的前后端交互的案例
简单的前后端交互的案例
简单的前后端交互的案例--在表单页面输入信息,该信息存入数据库
- 首先封装自己的数据库
//封装数据库
//导入mysql模块
const mysql = require ('mysql2');//创建数据库连接对象
const connection = mysql.createConnection({host:'localhost'. //数据库地址post:3306, //端口号user:'root', //数据库用户名password:'123456' //自己设置的数据库密码database:'dbms' //要连接的数据库
})//使数据库连接的对象对外可见
module.exports = connection;
- 写后台服务器(API接口)
//导入http模块,用户创建http服务
const http = require('http');//导入querystring模块,该模块是用来解析客户端提交的数据
const queryString = require('querystring');//导入数据库的配置模块,用于数据库的操作
const connection = require('../db/dbconfig') //刚才自己好封装数据库的地址//创建http服务服务器:对应的请求地址是http://localhost:3000/index
var server = http.createServer((req,res)=>{
//req:全称request,请求,是客户向浏览器发出询问
//res:全称response,响应,是客户请求完成后,服务器接收成功并向客户端响应(即把处理好的结果发送给客户服务器(页面))//获取客户端请求的地址
let clientUrl = req.url
//我们创建一个页面地址,先使用该页面地址
if(clientUrl === '/index'){let body = '' //用来保存客户端提交的请求数据//给请求对象绑定'data'事件,获取客户端的请求数据,并将数据保存到body中req.on('data',chunk =>{ //chunk内 存放的是 用户的数据,将他依次存放到body内body += chunk;})//给请求对象req绑定end事件,解析用户的请求数据req.on('end',()=>{let params = queryString.parse(body); //使用querystring的属性parse 将数据转化为键值对格式,方便解析//设置服务器端的头部信息,响应到页面res.writeHead(200,{'content-Type':'text/plain;charset=utf8'}) //设置数据响应到页面的格式,防止乱码//拼接相应字符串let res_str = "姓名:"+params.name+"\n"+"性别:"+params.gender+"\n"+"生日:"+params.birthday+"\n"+"电话"+params.phone+"\n"+"地址"+params.address;save(params); //先存入再响应数据插入成功了//将响应字符串发送给客户端res.wirte(res_str);//断开连接res.end();})}
})server.listen(3000);//绑定端口号//创建将数据保存到数据库的方法
function save(params){connection.query('insert into employee set?',{name:params.name,gender:params.gender,birthday:params.birthday,phone:params.phone,address:params.address},(err,resulet)=>{if (err){console.log(err)return;}console.log('插入数据成功!')connection.end(); //断开数据库连接})
}
先使用Postman来检测接口是否可用
去数据库查看,数据是否插入。
- 创建一个简易表单页面
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>简单的前后端的交互</title>
</head>
<body><form action="http://localhost:3000/index" method="post">姓名:<input type="text" name="name"><br><br>性别:<input type="text" name="gender"><br><br>生日:<input type="date" name="birthday"><br><br>电话:<input type="text" name="phone"><br><br>住址:<input type="text" name="address"><br><br><button type="submit">提交</button></form>
</body>
</html>
查看提交后,数据是否可以插入数据库
一个简单的前后端交互案例就写完啦!!!