我正在制作MEAN商店应用。我在将图像存储到数据库时遇到麻烦。我同时使用body-parser
和multer
。我们可以同时使用两种中间件吗?
这是server.js
文件:
var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var path = require('path');
var http = require('http');
var multer = require('multer');
var app = express();
var api = require('./server/routes/api');
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
var upload = multer({
dest: path.join(__dirname, '/server/public/images'),
});
app.use(express.static(path.join(__dirname + '/dist/meanshopcart')));
app.use('/api', api.router);
app.post('/userlogin', api.login);
app.post('/sign-up', api.signup);
app.post('/product', upload.single('productimage'), api.addProduct);
app.use(api.authenticate);
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, '/dist/meanshopcart/index.html'));
});
addProduct
函数:
function addProduct(req, res, next) {
console.log("adding new product");
var newProduct = new Product({
productName: req.body.productname,
productCategory: req.body.productcategory,
productDescription: req.body.productdescription,
productPrice: req.body.productprice
});
newProduct.productImage.data = fs.readFileSync(req.file);
newProduct.productImage.contentType = 'image/jpg';
newProduct.save(function(err) {
if (err) {
console.log("error saving product");
res.status(400).json({
success: false,
message: 'Error processing request ' + err
});
} else {
console.log("product inserted");
res.status(201).json({
success: true,
message: 'Product added successfully.'
});
}
});
}
module.exports = {
router,
signup,
login,
authenticate,
addProduct
};