node+MySQL 写一个简单的登录

准备一个表单

  • xxx.html文件里
  • method发起方法
  • action地址
    <body>
    <form method="post" action="http://localhost:8080">
    <input type="text" name="userName">
    <input type="password" name="userPwd">
    <input type="submit" value="登录">
    </form>
    </body>

准备一个js文件

  • 同级目录下,xxx.js
  • 测试时,启动node xxx.js
  • querystring是格式
  • 引入MySQL之前要先下载npm i mysql 初始化文件
const http = require('http')
const querystring = require('querystring')
const mysql = require('mysql')
const server = http.createServer((req, res) => {
let postVal = ''
req.on('data', (chunk) => {
postVal += chunk
})
req.on('end', () => {
let formVal = querystring.parse(postVal)
let userName = formVal.userName
let userPwd = formVal.userPwd
const connection = mysql.createConnection({
host: 'localhost', //Navicat连接信息
user: 'root', //Navicat连接信息
password: '123456',//Navicat连接信息
database: 'demo1',//创建的表,查询的用户表
port: 3306 //Navicat连接信息
})
//数据库信息
connection.connect()
//连接数据库
connection.query(
'select * from user where userName=? and userPwd=?',
[userName, userPwd],
(err, results, fields) => {
if (err) throw err
if (results.length > 0) {
res.writeHead(200, { 'Content-Type': 'text/html;charset=utf8' })
res.write('登录成功')
res.end()
}
}
)
connection.end()
})
})
server.listen(8080)//监听

以上是我学习笔记~~~