nodejs-用express重写留言板

关于留言板的总体介绍在《留言板-demo》里
下面直接用express框架开写

在写之前,为减少代码出错或者更改后服务器得重新重启,可以安装nodemon,这样每次文件有变动都会自动重启。
设置修改代码自动重启,这样不用每次都重启
安装一个第三方命令行工具

1
npm install --global nodemon

安装完毕后,使用

1
nodemon app.js

即可

1、安装express模块和art-template

1
npm i -S express art-template express-art-template

2、引入express模块

1
2
3
var express = require('express')

var app = express()

3、配置使用模板引擎

1
2
3
4
app.engine('html', require('express-art-template'))

//评论数据
var comments =[]

4、写路由(中间件)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//开放/public/,这样直接就把样式库开放了
app.use('/public/', express.static('./public/'))

//请求/,返回index.html
app.get('/', function (req, res) {
res.render('index.html', {
comments: comments
})
})
//请求/post,返回post.html
app.get('/post', function (req, res) {
res.render('post.html')
})
//写完评论后请求/pinglun,将评论添加到comments里,然后重定向到主页面
app.get('/pinglun', function (req, res) {
var comment = req.query
//添加评论时间
var date = new Date()
comment.dateTime = date.getFullYear() + '-' + (date.getMonth() + 1) +
'-' + date.getDate() + ' ' + date.getHours() +
':' + date.getMinutes() + ':' + date.getSeconds()
comments.unshift(comment)
//设置重定向
// res.statusCode = 302
// res.setHeader('Location', '/')
// res.send()
res.redirect('/')
})

5、打开监听,启动服务

1
2
3
app.listen(3000, function () {
console.log('running...')
})

下篇:结合mongodb的一个多人社区的案例(之前学的时候老师只讲了一部分,我会把案例做完整之后整理下来)

# nodejs

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×

// tidio机器人助手