我正在使用NodeJS样式的博客,由于某种原因,类别名称的变量显示为#{category.name},而其他变量值实际上显示了值。其次,当我为帖子提交图片时,它不会上传图片。任何帮助,看看我的代码中是否可能存在一些错误,将不胜感激。预先谢谢你。
app.js
var express = require("express");
var path = require("path");
var favicon = require("serve-favicon");
var logger = require("morgan");
var cookieParser = require("cookie-parser");
var bodyParser = require("body-parser");
var session = require("express-session");
var multer = require("multer");
var upload = multer({ dest: "./public/images" });
var expressValidator = require("express-validator");
var mongo = require("mongodb");
var db = require("monk")("localhost/nodeblog");
var routes = require("./routes/index");
var posts = require("./routes/posts");
var categories = require("./routes/categories");
var app = express();
app.locals.moment = require("moment");
app.locals.truncateText = function(text, length) {
var truncatedText = text.substring(0, length);
return truncatedText;
};
// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "pug");
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger("dev"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
// Express Session
app.use(
session({
secret: "secret",
saveUninitialized: true,
resave: true
})
);
// Express Validator
app.use(
expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split("."),
root = namespace.shift(),
formParam = root;
while (namespace.length) {
formParam += "[" + namespace.shift() + "]";
}
return {
param: formParam,
msg: msg,
value: value
};
}
})
);
// Connect-Flash
app.use(require("connect-flash")());
app.use(function(req, res, next) {
res.locals.messages = require("express-messages")(req, res);
next();
});
// Make our db accessible to our router
app.use(function(req, res, next) {
req.db = db;
next();
});
app.use("/", routes);
app.use("/posts", posts);
app.use("/categories", categories);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error("Not Found");
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get("env") === "development") {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render("error", {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render("error", {
message: err.message,
error: {}
});
});
module.exports = app;
index.pug
extends layout
block content
if posts
each post, i in posts
.post
h1
a(href='/posts/show/#{post._id}')
=post.title
p.meta Posted in
a(href='/categories/show/#{post.category}') #{post.category} by #{post.author} on #{moment(post.date).format("MM-DD-YYYY")}
img(src='/images/#{post.mainimage}')
!=truncateText(post.body,400)
a.more(href='/posts/show/#{post._id}') Read More
addpost.pug
extends layout
block content
h1=title
ul.errors
if errors
each error, i in errors
li.alert.alert-danger #{error.msg}
form(method='post', action='/posts/add', enctype="multipart/form-data")
.form-group
label Title:
input.form-control(name='title', type='text')
.form-group
label Category
select.form-control(name='category')
each category, i in categories
option(value='#{category.name}') #{category.name}
.form-group
label Body
textarea.form-control(name='body', id='body')
.form-group
label Main Image:
input.form-control(name='mainimage', type='file')
.form-group
label Author:
select.form-control(name='author')
option(value='Erik Robles') Erik Robles
option(value='John Doe') John Doe
input.btn.btn-default(name='submit',type='submit',value='Save')
script(src='/ckeditor/ckeditor.js')
script
| CKEDITOR.replace('body');
addcategory.pug
extends layout
block content
h1=title
ul.errors
if errors
each error, i in errors
li.alert.alert-danger #{error.msg}
form(method='post', action='/categories/add')
.form-group
label Name:
input.form-control(name='name', type='text')
input.btn.btn-default(name='submit',type='submit',value='Save')
posts.js
var express = require("express");
var router = express.Router();
var multer = require("multer");
var upload = multer({ dest: "./public/images" });
var mongo = require("mongodb");
var db = require("monk")("localhost/nodeblog");
router.get("/add", function(req, res, next) {
var categories = db.get("categories");
categories.find({}, {}, function(err, categories) {
res.render("addpost", {
title: "Add Post",
categories: categories
});
});
});
router.post("/add", upload.single("mainimage"), function(req, res, next) {
// Get Form Values
var title = req.body.title;
var category = req.body.category;
var body = req.body.body;
var author = req.body.author;
var date = new Date();
// Check Image Upload
if (req.file) {
var mainimage = req.file.filename;
} else {
var mainimage = "noimage.jpg";
}
// Form Validation
req.checkBody("title", "Title field is required").notEmpty();
req.checkBody("body", "Body field is required").notEmpty();
// Check Errors
var errors = req.validationErrors();
if (errors) {
res.render("addpost", {
errors: errors
});
} else {
var posts = db.get("posts");
posts.insert(
{
title: title,
body: body,
category: category,
date: date,
author: author,
mainimage: mainimage
},
function(err, post) {
if (err) {
res.send(err);
} else {
req.flash("success", "Post Added");
res.location("/");
res.redirect("/");
}
}
);
}
});
module.exports = router;
index.js
var express = require("express");
var router = express.Router();
var mongo = require("mongodb");
var db = require("monk")("localhost/nodeblog");
/* GET home page. */
router.get("/", function(req, res, next) {
var db = req.db;
var posts = db.get("posts");
posts.find({}, {}, function(err, posts) {
res.render("index", { posts: posts });
});
});
module.exports = router;
categories.js
var express = require("express");
var router = express.Router();
var mongo = require("mongodb");
var db = require("monk")("localhost/nodeblog");
router.get("/show/:category", function(req, res, next) {
var posts = db.get("posts");
posts.find({ category: req.params.category }, {}, function(err, posts) {
res.render("index", {
title: req.params.category,
posts: posts
});
});
});
router.get("/add", function(req, res, next) {
res.render("addcategory", {
title: "Add Category"
});
});
router.post("/add", function(req, res, next) {
// Get Form Values
var name = req.body.name;
// Form Validation
req.checkBody("name", "Name field is required").notEmpty();
// Check Errors
var errors = req.validationErrors();
if (errors) {
res.render("addpost", {
errors: errors
});
} else {
var categories = db.get("categories");
categories.insert(
{
name: name
},
function(err, post) {
if (err) {
res.send(err);
} else {
req.flash("success", "Category Added");
res.location("/");
res.redirect("/");
}
}
);
}
});
module.exports = router;
如果我缺少任何内容,请告诉我,以便进行适当的编辑。再次谢谢你。 附言按结构是:
routes
categores.js
index.js
posts.js
views
addcategory.pug
addpost.pug
error.pug
index.pug
layout.pug
app.js
答案 0 :(得分:0)
我使用的代码很旧(大约在2016年),不再起作用。在调用变量名时,必须从第一个选项变量中删除花括号,哈希和引号。这是应在“类别选项”部分中阅读的代码: addpost.pug
.form-group
label Category
select.form-control(name='category')
each category, i in categories
option(value=category.name) #{category.name}
我希望这个答案可以帮助遇到同样问题的人。