. Advertisement .
..3..
. Advertisement .
..4..
Is your project struggling with this “Error: Route.get() requires a callback function but got a [object Undefined] at app.js“. Confused about how to handle it? Don’t worry, keep following our article. Here we help you figure out how to solve it.
What is “Error: Route.get() requires a callback function but got a [object Undefined] at app.js”
Below is the program error:
//Controllers places this is the controllers file for the crud places
const Place = require('../models/Place');
exports.getAllPlacess = async (req, res) => {
try {
const places = await Place.find().populate('owner');
res.status(200).json({ places });
} catch (error) {
res.status(400).json({ message: `${error}` });
}
};
exports.getPlace = async (req, res) => {
try {
const { id } = req.params;
const place = await (await Place.findById(id)).populate('owner');
res.status(200).json({ place });
} catch (error) {
res.status(400).json({ message: `${error}` });
}
};
exports.createPlace = async (req, res) => {
try {
const { name, typePlace, address } = req.body;
const owner = req.user.id;
const place = await Place.create({
name,
typePlace,
address,
owner,
});
res.status(201).json({ place });
} catch (error) {
res.status(400).json({ message: `${error}` });
}
};
exports.updatePlace = async (req, res) => {
try {
const { id } = req.params;
const { name, typePlace, address } = req.body;
const place = await Place.findByIdAndUpdate(id, {
name,
typePlace,
address,
owner,
});
res.status(200).json({ place });
} catch (error) {
res.status(400).json({ message: `${error}` });
}
};
exports.deletePlace = async (req, res) => {
try {
const { id } = req.params;
await Place.findByIdAndDelete(id);
res.status(200).json({ message: 'Deleted Recipe' });
} catch (error) {
res.status(400).json({ message: `${error}` });
}
};
//Route this the file for the routes
const express = require('express');
const router = express.Router();
const uploadConfig = require('../config/cloudinary');
const {
getAllPlaces,
getPlace,
createPlace,
updatePlace,
deletePlace,
} = require('../controllers/places');
router.post('/upload', uploadConfig.single('photo'), (req, res, next) => {
if (!req.file) {
next(new Error('No file uploades'));
}
res.status(201).json({ secure_url: req.file.secure_url });
});
//CRUD PLACES
router.get('/places', getAllPlaces);
router.get('/places/:id', getPlace);
router.post('/places/create', createPlace);
router.put('/places/edit/:id', updatePlace);
router.delete('/places/delete/:id', deletePlace);
module.exports = router;
//app.js
require('dotenv').config();
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const express = require('express');
const mongoose = require('mongoose');
const logger = require('morgan');
const path = require('path');
const colors = require('colors');
const cors = require('cors');
const session = require('express-session');
mongoose
.connect(process.env.DB, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
})
.then((x) =>
console.log(
`Connected to Mongo! Database name: "${x.connections[0].name}"`.cyan
.underline.bold
)
)
.catch((err) => console.error('Error connecting to mongo', err.red));
const app_name = require('./package.json').name;
const debug = require('debug')(
`${app_name}:${path.basename(__filename).split('.')[0]}`
);
const app = express();
app.use(
cors({
credentials: true,
origin: [process.env.FRONTENDPOINT],
})
);
app.use(
session({
resave: false,
saveUninitialized: true,
secret: process.env.SECRET,
cookie: { maxAge: 1000 * 60 * 60 },
})
);
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(logger('dev'));
const index = require('./routes/index');
app.use('/', index);
const recipe = require('./routes/recipe-routes');
app.use('/api', recipe);
const place = require('./routes/places-routes');
app.use('/api', place);
// Uncomment this line for production
// app.get('/*', (req, res) => res.sendFile(__dirname + '/public/index.html'));
module.exports = app;
Solution For “Error: Route.get() requires a callback function but got a [object Undefined] at app.js”
Method 1: Edit this command line become
To solve the error “Error: Route.get() requires a callback function but got a [object Undefined] at app.js” is very simple. According to the above program, the command line you entered has a spelling mistake. See the error below:
exports.getAllPlacess = function() { ... }
const {
getAllPlaces,
getPlace,
createPlace,
updatePlace,
deletePlace,
} = require('../controllers/places');
There was a difference between the two output and import command lines. Edit this command line
exports.getAllPlacess = function() { ... }
become:
exports.getAllPlaces = function() { ... }
Method 2: Let’s follow the guide below
Excepting the solution mentioned above, there is another way for you to solve the error “Error: Route.get() requires a callback function but got a [object Undefined] at app.js”. Let’s follow the guide below:
The todo.all function in the tutorial returns a callback object. The router.get needs this to function syntax.
According to this documentation:
router.METHOD(path, [callback, …] callback)
The router.METHOD() methods provide the routing functionality in Express, where METHOD is one of the HTTP methods, such as GET, PUT, POST, and so on, in lowercase. Thus, the actual methods are router.get(), router.post(), router.put(), and so on.
To access the correct callback object for your router, you must still specify the array of callback objects in the todo files.
The array of callback objects in todo.js is what you access when you write todo.all, as you can see from your tutorial:
module.exports = {
all: function(req, res){
res.send('All todos')
},
viewOne: function(req, res){
console.log('Viewing ' + req.params.id);
},
create: function(req, res){
console.log('Todo created')
},
destroy: function(req, res){
console.log('Todo deleted')
},
edit: function(req, res){
console.log('Todo ' + req.params.id + ' updated')
}
};
Conclusion
The above article has provided how to handle when you encounter “Error: Route.get() requires a callback function but got a [object Undefined] at app.js“. Hope you find the error and get it resolved soon. Thanks for reading!
Read more
Leave a comment