【问题标题】:Cannot POST /images | MongoDB y Mongoose无法发布/图像 | MongoDB 和 Mongoose
【发布时间】:2020-04-14 03:47:18
【问题描述】:

我正在和一个朋友在 NodeJS 中开发一个项目,我们正在使用 express、Mongoose,当将图像上传到服务器时,它会向我们抛出这个错误:Cannot POST / images 这里我留下代码以防有人可以帮助我:

const fs = ('fs-extra');
const path = ('path');
const md5 = ('md5');

const ctrl = {};

const Image = require('../models/image.js');

ctrl.create = (req, res) => {
  const saveImage = async () => {
    const imgUrl = randomNumber();
    const images = await Image.find({ filename : imgUrl});
    if(images.length > 0) {
      saveImage()
    } else {
      const imageTempPath = req.file.path;
      const ext = path.extname(req.file.originalname).toLowerCase();
      const targetPath = path.resolve('/src/public/upload/${imgUrl}${ext}');

      if(ext == '.png' || ext == '.jpg' || ext == '.gif' || ext == '.jpeg') {
        await fs.rename(imageTempPath, targetPath);
        const newImg = new Image({
          filename: imgUrl + ext
        });
        const imageSaved = await newImg.save();
        res.redirect('/images/' + imageSaved.uniqueId);
      } else {
        await fs.unlink(imageTempPath);
        res.status(500).json({ error: 'Solo se permiten Imagenes'})
      }
    }
  };
  saveImage();
};

module.export = ctrl;

这是我用来上传图片的控制器,这是模型:

  const mongoose = require('mongoose');
const { Schema } = mongoose;
const path = require('path');

const ImageSchema = new Schema({
  filename: { type: String }
});

ImageSchema.virtual('uniqueId')
  .get(function () {
    return this.filename.replace(path.extname(this.filename), '');
  });

module.exports = mongoose.model('Image', ImageSchema); 

最后这是我用来上传图片的路径(除了登录和用户注册等一些路径):

const router = require('express').Router();
const passport = require('passport');
const multer = require('multer');
const path = require('path');
const fs = require('fs-extra');
const image = require('../controllers/image');

module.exports = app => {
  router.post('/images', image.create);
}

router.get('/', (req, res, next) => {
  res.render('index');
});

router.get('/signup', (req, res, next) => {
  res.render('signup');
});

router.post('/signup', passport.authenticate('local-signup', {
  successRedirect: '/profile',
  failureRedirect: '/signup',
  failureFlash: true
}));

router.get('/signin', (req, res, next) => {
  res.render('signin');
});

router.post('/signin', passport.authenticate('local-signin', {
  successRedirect: '/profile',
  failureRedirect: '/signin',
  failureFlash: true
}));

module.exports = router;

router.use((req, res, next) => {
  isAuthenticated(req, res, next);
  next();
});

router.get('/profile', (req, res, next) => {
  res.render('profile');
});

router.get('/logout', (req, res, next) => {
  req.logout();
  res.redirect('/');
});

function isAuthenticated(req, res, next) {
  if(req.isAuthenticated()) {
    return next();
  }

  res.redirect('/')
}

如果你能帮助我,我将不胜感激 谢谢。

【问题讨论】:

  • 请用英文发表您的问题。
  • 准备好我的帖子是英文的,抱歉我的英文不好,但它会很有帮助,请帮助我。

标签: javascript mongodb express mongoose


【解决方案1】:

根据THIS文章,需要使用multer在MongoDB中保存图片。

这里重要的一点是我们的数据类型是Buffer,它允许我们将图像存储为数组形式的数据。

const multer = require('multer');

mongoose.connect(‘url_here’);

const Item = new ItemSchema(
  { img: 
      { data: Buffer, contentType: String }
  }
);

const Item = mongoose.model('Clothes',ItemSchema);

app.use(multer({ dest: ‘./uploads/’,
 rename: function (fieldname, filename) {
   return filename;
 },
}));

app.post(‘/api/photo’,function(req,res){
 var newItem = new Item();
 newItem.img.data = fs.readFileSync(req.files.userPhoto.path)
 newItem.img.contentType = ‘image/png’;
 newItem.save();
});

或者关注这个帖子。 Store an image in MongoDB using Node.js/Express and Mongoose

【讨论】:

    猜你喜欢
    • 2011-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    • 2015-09-20
    • 2014-11-09
    • 2012-02-07
    • 2015-03-30
    相关资源
    最近更新 更多