自动化脚手架工具:vue-cli、webpack-cli和定制化脚手架工具开发。javascript
中间层:
保持先后端分离的前提下,使用node搭建Web Server简易服务器,用来作页面的服务端渲染和数据接口的合并。css
灵活运用node辅助项目架构:
好比使用node作cache缓存。html
全栈开发:
使用node作小型的商业项目、我的博客的全栈。vue
mysql官网下载安装MySQL Server。安装好后,登录mysql,看mysql是否链接成功,以下图所示: java
create DATABASE user;
use user;
create table userlist(
id int primary key auto_increment,
username char(30) unique,
password char(30)
);
复制代码
insert into userlist values(1,'zhangsan','123456');
复制代码
执行插入SQL语句后,userlist表中有以下数据: node
node项目中使用npm先安装mysql工具包:mysql
npm install mysql --save
复制代码
建立server.js,用mysql包链接mysql:jquery
const mysql = require('mysql');
// 创建数据库链接池
const pool = mysql.createPool({
host: '127.0.0.1',
port: '3306',
user: 'root',
password: 'root123456',
database: 'user'
})
复制代码
client端: 建立index.htmlwebpack
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登陆</title>
<script src="https://cdn.bootcss.com/jquery/2.2.1/jquery.js"></script>
</head>
<body>
<input type="text" id="username"/>
<input type="password" id="password"/>
<button id="login">登陆</button>
<script type="text/javascript">
$('#login').click(function(){
$.ajax({
type: 'POST',
url: '/login',
dataType: 'json',
data: JSON.stringify({
username: $('#username').val(),
password: $('#password').val()
}),
success: function (data) {
if(data.success) {
window.location.href = '/welcome';
}else{
alert('帐号密码错误')
}
}
});
})
</script>
</body>
</html>
复制代码
server端:web
// server.js
const fs = require('fs');
const express = require('express');
const app = express();
const { query } = require('./query-db');
app.get('/', function(req, res) {
let file = fs.readFileSync('./index.html');
let _data = file.toString();
res.setHeader('Content-type','text/html;charset=UTF-8')
res.send(_data);
})
app.post('/login', function(req, res) {
let reqData = "";
res.setHeader('Content-type','text/json;charset=UTF-8')
req.on('data', function(data){
reqData += data
});
req.on('end', async function(){
let dataOb = JSON.parse(reqData);
let word = "select * from userlist where username='";
word += dataOb.username + "'";
word += " and password='";
word += dataOb.password + "'";
let result = await query(word);
if(result && result.length > 0) {
// 若是要在express里面使用session需安装express-session
res.setHeader('Set-Cookie', 'username='+result[0].username)
res.send(JSON.stringify({
success: true,
message: '登陆成功!'
}))
}else{
res.send(JSON.stringify({
success: false,
message: '登陆失败!'
}))
}
})
})
app.get('/welcome', function(req, res) {
res.send('Login success!')
})
app.listen(3000);
复制代码
// query-db.js
const mysql = require('mysql');
const pool = mysql.createPool({
host: '127.0.0.1',
port: '3306',
user: 'root',
password: 'root123456',
database: 'user'
})
let query = function(sql) {
return new Promise((resolve, reject) => {
pool.query(sql, function(error, result, fields){
if (error) throw error;
resolve(result);
})
})
}
module.exports = { query };
复制代码
登陆功能结果图: