本地html连接数据库

一、随便写一个html登录页面

<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>测试登录页面</title>
	<style>
	body{
    width: 100%;
		background-image:url("./back2.jpg");
		background-repeat:no-repeat;
		background-size:100% ;
	}
	.login{
		float:right;
		margin-right:20vh;
	  margin-top:15vh;
		opacity:0.7;
		height: 35vh;
		width:50vh;
		background:#CCFF80;
		border-radius: 20px;
	}
	.title{
		font-size:30px;
		text-align:center;
	}
	.biao{
		margin-top:20px;
		font-size:20px;
		text-align:center;
	}
	</style>
</head>
<body>
	<div>
		<div class='login'>
			<div class='title'>欢迎登录</div>
			<div class='biao'>
				<form action="/login" method='post'>
					<label>用户:</label><input type="text" name='user'><br><br>
					<label>密码:</label><input type="password" name='pwd'><br>
					<input type="submit" value='登录' style='width:240px;height:30px;margin-top:25px;background:#B7FF4A'>
				</form>
			</div>
		</div>
	</div>
</body>
</html>

二、创建数据库

我通过脚本文件编写
通过mysql -uroot<‘拖拽脚本文件’ //加上回车执行
login.sql文件

set names utf8;
#如果存在,丢弃数据库
drop database if exists login;
create database login charset=utf8;
#进入数据库
use login;
#创建数据表
create table laptop(
  id int primary key auto_increment,#自增主键
  user varchar(40) unique,  #用户名
  password varchar(20) not null  #非空密码
);
#插入几条数据
insert into laptop values(1,'root','123456');
insert into laptop values(2,'123456','root');
insert into laptop values(3,'帅','666666');
insert into laptop values(4,'shuai','654321');
insert into laptop values(5,'1111','888888');

三、编写接口文档连接数据库与网页

这里我通过创建数据库池的方式,post方法传递数据,将获取到的数据与数据库里数据进行比较
login.js文件

const express=require('express');//引入express方法
const app=express();
const mysql=require('mysql');
const pool=mysql.createPool({
	host:'127.0.0.1',
	port:'3306',
	user:'root',
	password:'',
	database:'login',
	connectionLimit:15
});//数据库池连接数据库
app.listen(8080);//建立服务器
app.use(express.static('./'));//获取到html网页
app.use(express.urlencoded({
	extended:false
}));//将获取到的数据转化成对象
app.post('/login',(req,res,next)=>{
	console.log(req.body);//获取到我们输入数据对象,在控制台中可以得到我们输入的数据
	//pool.query方法中写查询的数据库语句
	pool.query('select * from laptop where user=?',[req.body.user],(err,result)=>{
		if(err){
			next(err);
			return		
		}
			if(result.length===0){
				console.log('用户名错误!')
				res.send('

用户名错误!

') }else{ if(result[0].password==req.body.pwd){ console.log('登录成功!') res.send('

登录成功!


'
+'欢迎用户:'+result[0].user) }else if(result[0].password!==req.body.pwd){ console.log('密码错误!') console.log(result[0].password) res.send('

密码错误!

') }} }) }) //错误排出 app.use((err,req,res,next)=>{ console.log(err); res.status(404).send({code:404,msg:'糟糕!出错了!'}) })

文件存放在同一个位置
在这里插入图片描述
在控制台中转到我们文件的目录
通过cd +目录名
如果不是在c盘通过e:转盘
输入 node login 加回车运行服务器(注意不要加分号!)
在浏览器中输入http://localhost:8080/login.html进行验证

你可能感兴趣的:(js,nodejs,node.js)