学生系统管理增删改查项目
1.使用express搭建服务器,先npm下载express框架。项目使用模板引擎express-art-template
npm install --save express
npm install --save art-template express-art-template //因为express-art-templatema模板引擎依赖于art-template包所以一并下载
2.引入express包
var express = require('express')
var fs = require('fs')//引入文件操作模块
3.创建服务器,开放可访问目录,这里开放了npm包路径下的资源以及我创建的文件夹/public/
var app = express()
app.use('/public/',express.static('./public/'))
app.use('/node_modules/',express.static('./node_modules/'))
4.设置请求事件,当浏览器向服务器发起默认’/'请求时,服务器渲染index.html页面返回客户端
app.get('/',function(req,res){
fs.readFile('./views/db.json',function(err,data){
if(err){
res.send('读取错误')
}
var date = data.toString()
console.log(JSON.parse(date).fruits);
res.render('index.html',{fruits : JSON.parse(date).fruits,
students : JSON.parse(date).students})//JSON.parse转换成jsond对象后.students拿到数据数组
})
})
5.设置服务器ip和端口号(默认ip为127.0.0.1,设置端口号为3000)
app.listen(3000,function(){
console.log('running')
})