- node.js项目
node.js
是基于 chrome V8引擎的JavaScript运行环境
- 安装项目
npm install
- 安装nodemon监视node.js应用程序发生的任何改变
npm install -g nodemon
并在package.json
文件下更改scripts
中数据
"scripts": {
"start": "nodemon ./bin/www"
},
- 安装MySQL模块
npm install mysql
// 引入MySQL模块
var mysql = require('mysql')
// 数据库连接池
var pool = mysql.createPool({
connectionLimit: 20,
host: '127.0.0.1',
user: 'root',
password: '123', //数据库密码
database: 'ddd' //使用的库名
})
// 暴露接口
module.exports = pool
- 安装跨域访问模块
npm install cors --save
在app.js
中引入该模块
// 引入模块
var cors = require('cors')
//注册该模块
app.use(cors())
- 配置文件
//引入express模块
var express = require('express');
//创建路由对象
var router = express.Router();
// 引入mysql 配置文件
var pool = require('../config/config')
// 接口地址:http://127.0.0.1:3000/search
router.get('/search',function(req,res,next){
pool.getConnection(function(err,conn){
if(err){
console.log('连接数据库失败')
} else{
let sql = 'select * from stu'
conn.query(sql,function(error,results){
if(error){
console.log('查询失败')
return
}
res.send(results)
})
conn.release()
}
})
})
module.exports = router;
- html 文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- 引入 bootstrap css样式 -->
<link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css">
<!-- 引入Vue.js -->
<script src="../../../jquery.js"></script>
<script src="../../../vue.js"></script>
</head>
<body>
<div id="app">
<table class="table table-border table-hover table-striped">
<thead>
<tr>
<th>编号</th>
<th>姓名</th>
<th>性别</th>
<th>地址</th>
<th>生日</th>
</tr>
</thead>
<tbody>
<tr v-for='item in people'>
<th>{{ item.sno }}</th>
<th>{{ item.sname }}</th>
<th>{{ item.sage }}</th>
<th>{{ item.saddress }}</th>
<th>{{ item.brithday | date }}</th>
</tr>
</tbody>
</table>
</div>
<script>
new Vue({
el:'#app',
data:{
people:[]
},
created:function(){
let self = this;
$.ajax({
url: 'http://127.0.0.1:3000/search',
type: 'get',
dataType: 'json',
success:function(data){
self.people = data;
}
})
},
filters:{
date:function(value){
let date = new Date(value);
let year = date.getFullYear();
let month = date.getMonth()+1;
let day = date.getDate()
month = month<10 ? '0'+month:month
day = day<10 ? '0'+day:day
return `${year}--${month}--${day}`;
}
}
})
</script>
最终效果