TypeError:尝试 multer 模块时出错

问题描述 投票:0回答:1

天才们大家好,我是后端技术的新手。我正在构建一个将文件和文本上传到数据库的项目,但收到一条错误消息。我使用 Nodejs 和 mongoDB 作为我的数据库。 我期待在这里得到建议。谢谢

下面是我的服务器代码。

const express = require('express');
const {default:mongoose} = require('mongoose');
const multer = require('multer');
const Storage = multer.diskStorage({
    destination: 'uploads',
    filename:(req, file, cb)=> {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
        cb(null, file.originalname);
    },
})    
const upload = multer({
    storage:Storage
}).single('image')
const Blog = require('./models/blog.js');
    
mongoose
    .connect("mongodb://127.0.0.1:27017/filesUpload") 
    .then(()=>{console.log('Mongo server has started')})
    .catch(()=>{console.log('Connection to Mongo Failed')})

const app = express();
const port = 3000;
app.set('views engine', 'ejs')
app.use(express.static("public"));
app.use(express.urlencoded());
app.use(express.json());

app.get("/", async (req, res)=>{
    const blogs = await Blog.find()
    res.render('index.ejs', {title: 'HOME', blogs})    
})

app.post("/blogs/create", (req, res)=>{    
    upload = (req, res, (err)=>{
        if (err){
            console.log(err)
        }
        else{    
            const blog = new Blog({
                title: req.body.title,
                snippet: req.body.snippet,
                body: req.body.body,
                image: {
                    date: req.file.filename,
                    contentType: "image/jpg"
                }
            });    
            blog.save().then(()=>{
                res.redirect('/')
            }).catch((err)=>{
                console.log(err)
            }) 
        }
    })
})    

app.listen(port, ()=>{
    console.log('Server is currently running')
})

下面是我点击发布请求时收到的错误消息:

TypeError: Assignment to constant variable.
    at C:\Users\go\Desktop\not\files\app.js:53:12
    at Layer.handle [as handle_request] (C:\Users\go\Desktop\not\files\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\go\Desktop\not\files\node_modules\express\lib\router\route.js:144:13)
    at Route.dispatch (C:\Users\go\Desktop\not\files\node_modules\express\lib\router\route.js:114:3)
    at Layer.handle [as handle_request] (C:\Users\go\Desktop\not\files\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\go\Desktop\not\files\node_modules\express\lib\router\index.js:284:15
    at Function.process_params (C:\Users\go\Desktop\not\files\node_modules\express\lib\router\index.js:346:12)
    at next (C:\Users\go\Desktop\not\files\node_modules\express\lib\router\index.js:280:10)
    at jsonParser (C:\Users\go\Desktop\not\files\node_modules\body-parser\lib\types\json.js:119:7)
    at Layer.handle [as handle_request] (C:\Users\go\Desktop\not\files\node_modules\express\lib\router\layer.js:95:5)
node.js mongodb express ejs multer
1个回答
0
投票

您的代码中似乎存在一些错误导致了该问题。这是经过更正的代码的重新格式化版本:

const express = require('express');
const mongoose = require('mongoose');
const multer = require('multer');
const path = require('path'); // Add this for path handling
const Storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads'); // Corrected the destination path
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, uniqueSuffix + path.extname(file.originalname)); // Append the extension
  },
});
const upload = multer({
  storage: Storage,
}).single('image');
const Blog = require('./models/blog.js');

mongoose
  .connect('mongodb://127.0.0.1:27017/filesUpload', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => {
    console.log('Mongo server has started');
  })
  .catch(() => {
    console.log('Connection to Mongo Failed');
  });

const app = express();
const port = 3000;

app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use(express.urlencoded({ extended: true })); // Add { extended: true }
app.use(express.json());

app.get('/', async (req, res) => {
  const blogs = await Blog.find();
  res.render('index.ejs', { title: 'HOME', blogs });
});

app.post('/blogs/create', (req, res) => {
  upload(req, res, (err) => {
    if (err) {
      console.log(err);
    } else {
      const blog = new Blog({
        title: req.body.title,
        snippet: req.body.snippet,
        body: req.body.body,
        image: {
          date: req.file.filename,
          contentType: 'image/jpg',
        },
      });
      blog
        .save()
        .then(() => {
          res.redirect('/');
        })
        .catch((err) => {
          console.log(err);
        });
    }
  });
});

app.listen(port, () => {
  console.log('Server is currently running');
});

对代码所做的更改和更正:

1.添加路径模块,正确处理文件扩展名。 2.修复存储配置中的目标路径。 3.将app.set('views engine', 'ejs')更改为app.set('view engine', 'ejs')。 4.在express.urlencoded()中间件中添加了{extended: true}。 5.将上传变量的重新分配更改为upload(req, res, ...) 正确调用中间件。

© www.soinside.com 2019 - 2024. All rights reserved.