简体   繁体   English

无法发布/图像 | MongoDB 和 Mongoose

[英]Cannot POST /images | MongoDB y Mongoose

I am developing a project with a friend in NodeJS and we are using express, Mongoose and when uploading images to the server it throws us this error: Cannot POST / images Here I leave the code in case someone can help me please:我正在与 NodeJS 中的朋友开发一个项目,我们使用的是 express,Mongoose,当将图像上传到服务器时,它会抛出这个错误:无法发布/图像在这里我留下代码以防有人可以帮助我:

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;

This is the controller that I have for uploading images and this is the model:这是我用于上传图像的 controller,这是 model:

  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); 

And finally this is the route I use for uploading images (in addition to having some routes such as login and user registration):最后这是我用来上传图片的路径(除了一些路径,比如登录和用户注册):

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('/')
}

I would appreciate it very much if you could help me Thank you.如果您能帮助我,我将不胜感激谢谢。

You need to use multer to save images in MongoDB according to THIS article.根据这篇文章,您需要使用multer将图像保存在 MongoDB 中。

The important takeaway here is that our data type is a Buffer , which allows us to store our image as data in the form of arrays.这里重要的一点是我们的数据类型是Buffer ,它允许我们将图像存储为 arrays 形式的数据。

 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(); });

Or follow this post.或者关注这个帖子。 Store an image in MongoDB using Node.js/Express and Mongoose 使用 Node.js/Express 和 ZCCADCDEDB567ABAE643E15DCF0974E503Z 将图像存储在 MongoDB

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM