开发者问题收集

错误:Route.get() 需要回调函数但是得到了 [object Undefined] Node.js

2023-05-18
685

我正在学习为管理员制作网络音乐,您可以在其中上传 mp3 文件,但我遇到了以下错误 错误:Route.get() 需要回调函数,但得到了 [object Undefined] 在 Route。[as get] (C:\Users\ray\Musik\node_modules\express\lib\router\route.js:211:15) 在 proto。[as get] (C:\Users\ray\Musik\node_modules\express\lib\router\index.js:521:19) 在 Object。 (C:\Users\ray\Musik\route\lagu.js:20:8) 在 Module._compile (node:internal/modules/cjs/loader:1254:14) 在 Module._extensions..js (node:internal/modules/cjs/loader:1308:10) 在 Module.load (node:internal/modules/cjs/loader:1117:32) 在 Module._load (node:internal/modules/cjs/loader:958:12) 在 Module.require (node:internal/modules/cjs/loader:1141:19) 在 require (node:internal/modules/cjs/helpers:110:18) 在 Object. (C:\Users\ray\Musik\index.js:3:14)

Node.js v18.16.0

这是我的代码 index.js

const playlist = require('./route/playlist');
const artis = require('./route/artis');
const lagu = require('./route/lagu');
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();

let dev_db_url = 'mongodb://127.0.0.1:27017/musik';
let mongoDB = process.env.MONGODB_URI || dev_db_url;
mongoose.connect(mongoDB);
mongoose.Promise = global.Promise;
let db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.text({ type: '/' }));
app.set('view engine', 'ejs')
app.use('/lagu',lagu)
app.use('/artis',artis)
app.use('/playlist',playlist)

app.listen(1234, () => {
    console.log('Server is up and running on port number ' + 1234);
});

lagu.js

const express = require('express');
const router = express.Router();
const laguController = require('../controller/laguController');
const multer = require('multer');

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/');
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname);
  }
});

const upload = multer({ storage: storage });

router.get('/', laguController.index);
router.get('/tambah', laguController.tambah);
router.post('/create', upload.single('lagu'), laguController.store);
router.get('/:id', laguController.lagu_details);
router.post('/:id/update', laguController.update);
router.post('/:id/destroy', laguController.destroy);

module.exports = router;

laguController.js

const Lagu = require('../model/Lagu');
const moment = require('moment');
const { exec } = require('child_process');
const ffprobePath = require('@ffprobe-installer/ffprobe').path;
const multer = require('multer');
const path = require('path');

// Multer configuration
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/');
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
    const ext = path.extname(file.originalname);
    cb(null, file.fieldname + '-' + uniqueSuffix + ext);
  }
});

const upload = multer({ storage: storage });

exports.index = async function (req, res) {
  try {
    let lagu = await Lagu.find();
    return res.render('../views/lagu/index', { lagu, moment });
  } catch (err) {
    console.log(err);
    return res.status(500).send('Error retrieving lagu');
  }
};

exports.tambah = async function (req, res) {
  return res.render('../views/lagu/tambah');
};

exports.store = function (req, res) {
  upload.single('lagu')(req, res, function (err) {
    if (err) {
      console.log(err);
      return res.status(500).send('Error uploading file');
    }

    const laguFileName = req.file.filename;
    const filePath = `uploads/${laguFileName}`;

    exec(
      `${ffprobePath} -v error -select_streams a:0 -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "${filePath}"`,
      (error, stdout) => {
        if (error) {
          console.log(error);
          return res.status(500).send('Error reading duration');
        }

        const duration = parseFloat(stdout);
        const size = req.file.size;

        let lagu = new Lagu({
          judul_lagu: req.body.judul_lagu,
          artis: req.body.artis,
          album: req.body.album,
          durasi: duration.toFixed(2),
          size: size.toString(),
          lagu: filePath
        });

        // Periksa validasi sebelum menyimpan
        const validationErrors = lagu.validateSync();
        if (validationErrors) {
          const errors = Object.values(validationErrors.errors).map(err => err.message);
          console.log(errors);
          return res.status(400).send(errors.join('\n'));
        }

        lagu.save()
          .then((data) => {
            res.redirect('/lagu');
          })
          .catch((err) => {
            console.log(err);
            res.status(500).send('Error storing lagu');
          });
      }
    );
  });
};

你能帮助我吗,谢谢你邀请我

2个回答

据我所知, laguController 不会导出 lagu_details ,因此在执行以下操作时:

router.get('/:id', laguController.lagu_details);

Router.get() 收到未定义的结果,而它需要回调。

axtck
2023-05-18

我遇到了同样的问题,并通过以下方法解决了:

Route.get() 需要回调函数,但得到了“对象未定义”

在恢复时,您需要向每个端点返回一些响应。我建议您在 api 上创建新层,即服务层来处理所有规则。

Matheus Caetano
2023-05-18