node连接后端MySQL,前端利用HTML
写了一个最简单的form表单做测试,输入账号密码之后node终端查询空,具体代码如下:
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",
user: "root",
password: "123456",
port: 3306,
database: "demo1"
})
// 连接
connection.connect();
// 查询
connection.query('select * from user where userName=? and userPwd=?', [userName, userPwd], (err,
result, fields) => {
if (err) throw err;
if (result.length > 0) {
res.writeHead(200, {'Content-type':'text/html;charset=utf8'})
res.write(result);
}
res.end();
})
connection.end();
})
})
server.listen(8080)
console.log('server is running...')
前端代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>node_test</title>
</head>
<body>
<form method="post" action="http://localhost:8080">
<input type="text" name="userUser"/>
<input type="password" name="userPwd"/>
<input type="submit" name="登录"/>
</form>
</body>
</html>
数据库截图如下:
node控制台如下: