I have an error while running a node express server:
index.js.
const
bodyParser = require('body-parser'),
express = require('express'),
path = require('path');
const config = require('./config');
const app = express();
const mongoose = require('mongoose');
const apiTodos = require('./api/todos');
// connection mongodb via mongoose;
mongoose.connect('mongodb://localhost:27017/todoslist', { useNewUrlParser: true });
app.use(bodyParser.json());
app.use('/api/todos', apiTodos);
app.use('/', express.static(path.resolve(app.get('appPath'))));
app.listen(config.port, (err) => {
if (err) { return console.log('Error:', err); }
console.log('Listening on port %d', config.port);
});
module.exports = app;
./api/todos(point in index.js)
const express = require('express');
const Router = express.Router();
const controller = require('./todos.controller');
let router = new Router();
router.get('/check', controller.check);
module.exports = router;
todos.constroller
const tasklist = require('./todos.model');
let check = new Promise((resolve, reject) => {
setTimeout(function() {
(req, res) => {
tasklist.find({})
.then(data => {
resolve(console.log(data));
// resolve(res.status(200).json({ doc: data }));
})
.then(err => {
console.log(err);
// res.status(503).json({ msg: err });
});
}
}, 300);
});
module.exports = check;
Error message:
node_modules\express\lib\router\index.js:138 debug('dispatching %s %s', req.method, req.url); ^
TypeError: Cannot read property 'method' of undefined
I don't know what I did wrong, how can I solve this?
after 6hours on that i got the probleme;
the probleme is how i module.exports "constrollers";
todos.controller
the wrong way:
const tasklist = require('./todos.model');
let check = new Promise((resolve, reject) => {
setTimeout(function() {
(req, res) => {
tasklist.find({})
.then(data => {
resolve(console.log(data));
// resolve(res.status(200).json({ doc: data }));
})
.then(err => {
console.log(err);
// res.status(503).json({ msg: err });
});
}
}, 300);
});
module.exports = check;
and the right way:
const tasklist = require('./todos.model');
module.exports = {
check: (req, res, next) => {
tasklist.find({})
.then(data => {
if (data === null) {
res.status(404).json({ errmsg: 'aucune Competences trouver' });
} else {
res.status(200).json({ errmsgok: 'cool', doc: data });
}
})
.catch(() => {
console.log(err);
});
}
};
i should have export modules as json type, and promise is not a problem it's your chose voilà
thx for all the help!!!