Node.js---express 生成器开发零碎知识点笔记
2017-05-31 本文已影响0人
飞鱼_JS
//安装生成器(安装一次即可)
npm install express-generator -g
//生成ejs 模板项目
express 项目目录名 --view=ejs
//ejs 模板设置为.html文件,文件保存在views目录下
app.set('views', path.join(__dirname, 'views'));
app.engine(".html",require("ejs").__express)
app.set('view engine', 'html');
//修改.json文件,使用supervisor 启动服务器
"start" :"supervisor ./bin/www"
//npm run start 启动服务器
//在www文件中设置mongoDB数据库连接
server.listen(port,onSuccessStart);
function onSuccessStart(){
console.log("服务器运行在:"+port)
var mongoose=require("mongoose")
mongoose.connect("mongodb://127.0.0.1:27017/shopdb")
var db=mongoose.connection;
db.on("error",()=>{
console.log("数据连接失败,请检查数据库是否开启")
})
db.once("open",()=>{
console.log("数据库连接成功了,可以实现增删改查")
})
}
//将相对路径转化为绝对路径
var path=require("path")
var User=require(path.join(__dirname,"/../models/User"))
//nodejs使用multer中间件上传混合表单提交(单文件和非文件普通文本域上传)
//前端表单设置----------------------------------------------------
<form class="form-inline" style="margin-bottom: 10px" method="POST" action="/admin/home" enctype="multipart/form-data">
<div class="form-group">
<label for="exampleInputFile "><span class="text-danger">banner04:</span></label>
<input type='text' name='id' value='banner04' hidden>
<input name="image" style="display: inline;margin-right: 162px" type="file" id="exampleInputFile">
<p style="display: inline" class="help-block">(图片尺寸为1225*100像素)</p>
</div>
<button style="margin-left:30px; " type="submit" class="btn btn-success"> 上 传 </button><span class="text-danger"><%=title%></span>
</form>
//后端路由设置------------------------------------------------------
var express = require('express');
var router = express.Router()
var path = require('path');
var fs = require("fs")
var Banner = require(path.join(__dirname, "../models/Banner.js"))
var multer = require('multer');
var upload = multer({ dest: "public/images/" })
router.get("/", function(req, res) {
res.render("admin/login")
console.log("admin")
})
router.get("/home", function(req, res) {
console.log("home")
res.render("admin/home", {
title: "未上传",
})
})
// 添加banner 图
router.post("/home", upload.single("image"), (req, res) => {
Banner.find({ id: req.body.id }).then((data) => {
console.log("data",data)
console.log("数据库查询成功")
if (data.length != 0) {
console.log("data", data[0].img)
fs.unlink("public/images/"+data[0].img, function(err){
if(err){
console.log("删除图片失败")
}
console.log("图片删除成功")
Banner.remove({ id: req.body.id }).then((suc2) => {
// console.log("suc2",suc2)
uploadData(req,res)
}, (err) => {
console.log("数据库原数据删除失败")
})
})
} else {
console.log("数据库为空,直接上传")
uploadData(req, res);
}
}, (err) => {
console.log("查询数据库失败")
})
})
// 该函数用于图片上传
function uploadData(req, res) {
if (req.file) {
var extname = path.extname(req.file.originalname)
var oldPath = "public/images/" + req.file.filename;
var newPath = "public/images/" + req.file.filename + extname;
console.log(oldPath, newPath)
fs.rename(oldPath, newPath, (err, data) => {
if (err) {
console.log("图片上传成功,修改失败")
} else {
req.body.img = req.file.filename + extname;
console.log("req.body", req.body)
Banner.create(req.body).then((data) => {
if (data) {
console.log("图片存入数据库")
res.render("admin/home", {
title: "已上传",
})
} else {
console.log("图片存入数据库,失败")
res.render("admin/home", {
title: "上传失败",
})
}
}, (err) => {
console.log("图片存入数据库时发生错误")
res.render("admin/home", {
title: "上传失败",
})
})
}
})
} else {
console.log("图片上传失败,请重试")
res.render("admin/home", {
title: "上传失败",
})
}
}
module.exports = router;
//文件上传,获取文件的后缀名
var exthname = path.extname(req.file.originalname);
//history.back() 返回上一个路径,保持页面不变,不写会显示空白页面
function showError(message,res){
var result=`<script>alert('${message}');history.back()</script>`
res.send(result)
}
//URL传值方法
//方法一:
//.html
<a href="/users/list?movieid=<%=movie._id%>&imageid=<%=movie.image%>" >删除本影片</a>
//路由
req.query.movieid
req.query.imageid
//----------------------------------
//方法二
//.html
<a href="/movie/<%=movie._id%>" >进入详情</a>
//路由
router.get("/movie/:id",function(req,res){
Movie.findById(req.params.id).then((data)=>{
var movie=data;
res.render("detail",{
movie
})
})
})
//post name传值
//.html
<input type="text" name="_id" hidden value="<%=movie._id%>">
//路由
req.body._id