版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_36146776/article/details/79044942
只贴出关键代码,具体的基础配置,在dos窗口中键入express -e phone,会自动帮我们设置好app.js的配置
为了让nodejs可以渲染html页面,在dos窗口中键入npm install ejs --save,会自动帮ejs的相关配置下载如node_modules文件夹下。
app.js的配置
并且在app.js中加入以下代码配置
//设置渲染模板为html
var
ejs =
require(
'ejs');
app.
engine(
'html',
ejs.
__express);
app.
set(
'view engine',
'html');
1、db.js
扫描二维码关注公众号,回复:
4465974 查看本文章
var mysql = require('mysql');
var connection = mysql.createPool({
host : 'localhost',
user : 'root',
password : '123',
database : 'shopping'
});
function query(sql,callback){
connection.getConnection(function(err,connection){
connection.query(sql,function(err,rows){
callback(err,rows);
connection.release();
})
})
}
exports.query = query;
Navicate直观查看
2、index.js
var express = require('express');
var router = express.Router();
var db = require("./db.js");
//以下是连接数据库的操作
router.get('/getDBList',function(req,res,next){
db.query('SELECT * FROM websites',function(err,rows){
res.send(rows);
})
})
module.exports = router;
3、dbList.html
<!DOCTYPE html>
<html>
<head>
<title>列表</title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<button id="btn1">click me</button>//此处是为了测试jquery用
<div ng-app="myapp">//angularjs
<div ng-controller="myController">
<button ng-click="clickMe()">点击我</button>
<table>
<caption>angularJS列表页</caption>
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>url</th>
<th>alex</th>
<th>country</th>
<th>content</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in dbList">
<td ng-bind="item.id"></td>
<td ng-bind="item.name"></td>
<td ng-bind="item.url"></td>
<td ng-bind="item.alexa"></td>
<td ng-bind="item.country"></td>
<td ng-bind="item.content"></td>
</tr>
</tbody>
</table>
</div>
</div>
<script src="/javascripts/jquery.js" type="text/javascript"></script>
<script src="/javascripts/angular.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$.get("/getDBList",function(data,status){
console.log(data)
});
})
});
</script>
<script>
angular.module('myapp',[])
.controller('myController',['$scope','$http',function($scope,$http){
$scope.clickMe = function(){
$http.get('/getDBList').success(function(response){
console.log(response);
$scope.dbList = response;
})
}
}])
</script>
</body>
</html>
4、启动:
在控制台中输入http://localhost:3000/dbList,点击按钮即可获得数据。
5、结果: