Node.js新闻添加的小案例
2018-06-24 本文已影响0人
playman
Node.js新闻添加的小案例
创建文件
- save文件夹
- admin.html
- shownews.ejs
admin.thml
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style media="screen">
form{
width: 800px;
margin: 0 auto;
border: 1px solid #4c4c4c;
padding: 10px;
}
</style>
</head>
<body>
<h1>新闻后台</h1>
<form class="" action="/addnews" method="post">
<label for="titile">新闻标题</label>
<input type="text" name="title" value="" id="title">
<br>
<label for="pic">新闻图片</label>
<input type="text" name="pic" value="" id="pic">
<br>
<label for="newssrc">新闻来源</label>
<input type="text" name="newssrc" value="" id="newssrc">
<br>
<label for="newstime">新闻时间</label>
<input type="text" name="newstime" value="" id="newstime">
<br>
<input type="submit" name="" value="提交新闻">
</form>
</body>
</html>
shownews.ejs
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>新闻</title>
</head>
<body>
<ul>
<% for(var i=0; i<newslist.length; i++){ %>
<li>
<h1><%= newslist[i].title %></h1>
<img src="<%= newslist[i].pic %>" alt="">
<p><%= newslist[i].newstime %></p>
<p><%= newslist[i].newssrc %></p>
</li>
<% } %>
</ul>
</body>
</html>
app.js
var express = require('express');
var app = express();
var request = require('request');
var bodyParser = require('body-parser');
var fs = require('fs');//文件的读写
app.use(express.static('./public/'));
app.set('views','./views');
app.set('view engine','ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
//添加新闻
app.post('/addnews', function (req,res) {
console.log(req.body);
fs.readFile('./save/news.json', function (err,data) {
var newslist;
if(data.toString() === ''){
newslist = [];
}else{
newslist = JSON.parse(data);
}
var news = {};
news.title = req.body.title;
news.pic = req.body.pic;
news.newssrc = req.body.newssrc;
news.newstime = req.body.newstime;
newslist.push(news);
var str = JSON.stringify(newslist);
fs.writeFile('./save/news.json',str,'UTF-8');
res.send('添加成功');
});
});
app.get("/news", function (req, res) {
fs.readFile('./save/news.json', function (err,data) {
var list = JSON.parse(data);
res.render('shownews',{newslist:list});
});
});
var server = app.listen(3000,function(){
console.log("server 3000 running!");
});
注意:相关的依赖包要导入
- "body-parser": "^1.16.1",
- "ejs": "^2.5.5",
- "express": "^4.14.1",
- "request": "^2.79.0"