在编辑产品时,如果输入无效,我将connect-flash与express-session一起使用以显示错误。问题是有时错误不会显示,我必须刷新页面才能看到它。
这是我在app.js上的代码
const session = require('express-session');
const MongoDBStore = require('connect-mongodb-session')(session);
const flash = require('connect-flash');
const store = new MongoDBStore({
uri: <my mongodb connection>,
collection: 'sessions',
});
app.use(session({
secret: 'my secret',
resave: false,
saveUninitialized: false,
store: store
}));
app.use(flash());
controller.js上的代码
const productValidator = (req, res, title, imageUrl, price, description) => {
let hasError = false;
const invalidTitle = validator.isEmpty(title);
const validImageUrl = validator.isURL(imageUrl);
const validPrice = validator.isNumeric(price);
const validDescription = validator.isLength(description, {min: 5});
if (invalidTitle) {
req.flash('error', {message: 'Title is required', input: 'title'});
hasError = true;
}
if (!validImageUrl) {
req.flash('error', {message: 'Image should be valid url', input: 'imageUrl'});
hasError = true;
}
if (!validPrice) {
req.flash('error', {message: 'Price should be number', input: 'price'});
hasError = true;
}
if (!validDescription) {
req.flash('error', {message: 'Description should be more than or equal 5 character', input: 'description'});
hasError = true;
}
return hasError;
}
module.exports.postEditProduct = async (req, res) => {
const backURL = req.header('Referer');
const prodId = req.body.productId;
const updatedTitle = req.body.title;
const updatedPrice = req.body.price;
const updatedImageUrl = req.body.imageUrl;
const updatedDesc = req.body.description;
try {
const product = await Product.findById(prodId);
if (product.userId.toString() !== req.user._id.toString()) {
return res.redirect('/');
}
const isNotValid = productValidator(req, res, updatedTitle, updatedImageUrl, updatedPrice, updatedDesc);
if (isNotValid) {
return res.redirect(backURL);
}
product.title = updatedTitle;
product.price = updatedPrice;
product.imageUrl = updatedImageUrl;
product.description = updatedDesc;
await product.save();
// console.log(product);
res.redirect('/admin/products');
} catch (e) {
res.status(400).send(e);
}
};
请帮助我对nodejs有点陌生。谢谢。