skip to Main Content

Im learning to make web music for admin where u can upload mp3 files, but I have this errors
Error: Route.get() requires a callback function but got a [object Undefined] at Route. [as get] (C:UsersrayMusiknode_modulesexpresslibrouterroute.js:211:15)
at proto. [as get] (C:UsersrayMusiknode_modulesexpresslibrouterindex.js:521:19)
at Object. (C:UsersrayMusikroutelagu.js:20:8)
at Module._compile (node:internal/modules/cjs/loader:1254:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1308:10)
at Module.load (node:internal/modules/cjs/loader:1117:32)
at Module._load (node:internal/modules/cjs/loader:958:12)
at Module.require (node:internal/modules/cjs/loader:1141:19)
at require (node:internal/modules/cjs/helpers:110:18)
at Object. (C:UsersrayMusikindex.js:3:14)

Node.js v18.16.0

This my code
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');
          });
      }
    );
  });
};

can u help me, and thanks for having me

2

Answers


  1. As far as I can see, laguController does not export lagu_details so when doing:

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

    Router.get() is receiving undefined while it expects a callback.

    Login or Signup to reply.
  2. I had the same trouble and solved by this:

    Route.get() requires callback functions but got a "object Undefined"

    On resume You need to return every endpoint some response. I recommend you creating new layer at your api, a service layer to processing all the rules.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search