1、使用express框架之后代码变得更加简洁,代码只有提供服务的js有所变动,其余的代码保持不变,需要重新加载express模块
var comments = [{
name: ‘张珊‘,
message: ‘今天天气好晴朗,处处好风光‘,
dataTime: ‘2021年05月19日22:58:30‘
},
{
name: ‘李四‘,
message: ‘今天天气好晴朗,处处好风光‘,
dataTime: ‘2021年05月19日22:58:30‘
},
{
name: ‘王五‘,
message: ‘今天天气好晴朗,处处好风光‘,
dataTime: ‘2021年05月19日22:58:30‘
},
{
name: ‘赵柳‘,
message: ‘今天天气好晴朗,处处好风光‘,
dataTime: ‘2021年05月19日22:58:30‘
},
{
name: ‘田七‘,
message: ‘今天天气好晴朗,处处好风光‘,
dataTime: ‘2021年05月19日22:58:30‘
},
{
name: ‘小八‘,
message: ‘今天天气好晴朗,处处好风光‘,
dataTime: ‘2021年05月19日22:58:30‘
}
]
var template = require(‘art-template‘);
var express = require(‘express‘);
var fs = require(‘fs‘);
var app = express();
app.use(‘/public‘, express.static(‘./public/‘));
app.get(‘/‘, function(req, res) {
fs.readFile(‘./view/index.html‘, function(err, data) {
if (err) {
return res.end(‘404 Not Found.‘);
}
data = data.toString();
var htmlStr = template.render(data, {
file: comments
});
// res.end(htmlStr);
res.send(htmlStr);
});
// res.send(‘hello 我是about!!‘);
});
app.get(‘/public‘, function(req, res) {
fs.readFile(‘./public/start.html‘, function(err, data) {
if (err) {
return res.send(‘404 Not Found.‘);
}
res.end(data);
});
});
app.get(‘/addMeg‘, function(req, res) {
fs.readFile(‘./view/index.html‘, function(err, data) {
if (err) {
return res.end(‘404 Not Found.‘);
}
// console.log(req.query);
var userData = req.query;
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1;
month = getTow(month);
var day = date.getDate();
day = getTow(day);
var hour = date.getHours();
hour = getTow(hour);
var minute = date.getMinutes();
minute = getTow(minute);
var second = date.getSeconds();
second = getTow(second);
var dataTime = year + ‘年‘ + month + ‘月‘ + day + ‘日‘ + hour + ‘:‘ + minute + ‘:‘ + second;
userData.dataTime = dataTime;
comments.unshift(userData);
res.statusCode = 302;
res.setHeader(‘Location‘,‘/‘);
res.end();
});
});
function getTow(data) {
if (data < 10) {
data = ‘0‘ + data;
}
return data;
}
app.listen(3000, function() {
console.log(‘app is running at port 30000‘);
});
结果与上一个一样。
原文:https://www.cnblogs.com/191080438qq/p/14797776.html