首先,我们先在数据库中创建两个表t_news,t_news_type;插入数据:
然后我们再写代码:
//加载模块express
var express = require("express");
var fs = require("fs");
//加载路径
var url = require("url");
//加载数据库
var mysql = require("mysql");
var app = express();
app.set('view engine','ejs');
//动态路径
app.set('views',__dirname '/views');
//静态路径
app.use(express.static(__dirname '/public'));
//加载路由
var router = express.Router;
//获取路径
router.get('/index',function(req,res){
//创建连接
var connection = getConnection();
//查询
excuteQuery("SELECT b.news_type_id,a.title ,a.news_id,a.t_date,b.name as typename from"
" t_news a JOIN t_news_type b on a.news_type_id = b.news_type_id WHERE b.news_type_id=1; ",connection,function(result){
//发送指定页面
res.render('qh/views',{args:result});
})
});
app.use('/action',router);
//获取数据
function excuteQuery(sql,connection,fun){
connection.query(sql,function(error,rows){
var result= "";
if(error){
result = {
"status":"500",
"message":"服务器错误"
}
}else{
result = {
"status":"200",
"message":"success",
"data":rows
}
}
fun(result );
});
}
//获取数据库
function getConnection (){
var connection = mysql.createConnection({
host: 'localhost',
user: 'dzlx',
password:'wm969926dzl',
port: '3306',
database: 'test'
})
connection.connect();
return connection;
}
app.listen(3001,function afterListen(){
console.log("express running ....");
})
在你的网页中插入:
更多专业前端知识,请上 【猿2048】www.mk2048.com