使用Multer将图像上传到mongoDB时,Heroku出错

时间:2020-07-06 16:38:00

标签: node.js mongodb express heroku mongoose

我开发了一个应用程序,用户可以使用multer上传图像,并可以在主屏幕上检索/查看图像。我正在使用MongoDB作为数据库,在本地它运行良好。即使使用MongoDB CL,它在本地运行也很好。但是,当我通过数据库连接链接将其部署到Heroku时,出现以下错误。

2020-07-06T16:21:38.008989+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=quiet-anchorage-51950.herokuapp.com request_id=146ff967-98bb-45e5-a234-4dbf9535abbe fwd="124.123.143.110" dyno= connect= service= status=503 bytes= protocol=https

这是我的app.js:

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const fs = require('fs');
var path = require('path');
var multer  = require('multer');

var storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'uploads')
    },
    filename: (req, file, cb) => {
        cb(null, file.fieldname + '-' + Date.now())
    }
});
var upload = multer({ storage: storage })

app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: false }));
app.set("view engine", "ejs");

mongoose.connect("mongodb+srv://<myname>:<removedpassword>@webdatabase.rbrhg.mongodb.net/<dbname>?retryWrites=true&w=majority", {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

我使用的图像架构:

const imgSchema = new mongoose.Schema({
    img: {
        data: Buffer,
        contentType: String
    }
});

我发布的上传图片的请求:

app.post('/imgupload', upload.single('image'), function (req, res, next) {
    var image = new Image({
        img: {
            data: fs.readFileSync(path.join(__dirname + '/uploads/' + req.file.filename)),
            contentType: 'image/png'
        }
    });
    image.save();
    res.render("app",{Name: req.body.username});
});

这是我的package.json文件:

{
  "name": "igwebsite",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node app.js"
  },
  "author": "",
  "license": "ISC",
  "engines": {
    "node": "12.16.3"
  },
  "dependencies": {
    "body-parser": "^1.19.0",
    "dotenv": "^8.2.0",
    "ejs": "^3.1.3",
    "express": "^4.17.1",
    "mongodb": "^3.5.9",
    "mongoose": "^5.9.21",
    "multer": "^1.4.2"
  }
}

我想要的是本地完美的网络应用可以在线工作,有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

您需要将文件/图像存储在AWS s3中 请参阅此https://www.npmjs.com/package/multer-s3

答案 1 :(得分:0)

谢谢,但是我解决了。我的问题是端口值,我使用的OR条件可能是错误的。也许只需要3000而不是Heroku提供的端口。

我所做的一切都改变了

app.listen(3000 || process.env.PORT,() => {
   console.log("Server is up at port "+process.env.PORT);
});

为此:

app.listen(process.env.PORT || 3000,() => {
   console.log("Server is up at port "+process.env.PORT);
});