Error: "node_modules/express/lib/router/index.js:458 Router.use() requires a middleware function but got a Object at Function.use"
Code:
const express = require('express');
const bodyParser = require('body-parser');
const mustacheExpress = require('mustache-express');
const pgp = require('pg-promise');
const port = process.env.PORT || 3000;
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.engine('html', mustacheExpress());
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));
const students = require('./controllers/students.js');
const houses = require('./controllers/houses.js');
app.use('/houses', houses);
app.use('/students', students);
app.get('/', (req, res) => res.render('home/index'));
app.listen(port, () => { console.log("Server started on " + port); });
module.exports = router;
controllers/students.js:
This is the first file which is linked to the index.js
const router = require('express').Router();
const Students = require('../models/students.js');
router.get('/',
Students.findAll, (req, res) => {
res.render('students/index', {studentsData: res.locals.allStudentsData})
});
router.get('/:id', Students.findById, (req, res) => {
res.render('students/show', res.locals.showStudent)
});
module.exports = router;
controllers/houses.js:
This is the second file which is linked to the index.js
const router = require('express').Router();
const Houses = require('../models/houses.js');
router.get('/',
Houses.findAll, (req, res) => {
res.render('houses/index', {housesData: res.locals.allHousesData})
});
router.get('/:id', Houses.findById, (req, res) => {
res.render('houses/show', res.locals.showHouse)
});
module.exports = router;
Related
I am working on Nodejs(Express.js),I am sending Form data to controller but not working for me,I am getting error "TypeError: Cannot read property 'name' of undefined in Nodejs", But Main problem is my code is working/getting data in "app.js" but i want to get data in "userController" because i want to use MVC strtucre,Here is my root.js
var express=require('express');
var router= express.Router();
var controllers= require('../controllers');
router.get('/', controllers.homeController.index);
router.get('/signup', controllers.userController.signup);
router.post('/signup', controllers.userController.save);
router.get('/login', controllers.userController.login);
router.get('/dash', controllers.userController.dash);
module.exports = router;
Here is my userController.js file
userController.save = function (req, res, next) {
var name = req.body.name;
console.log(name);
}
Here is my app.js, How can i get data in "userController" instead of "app.js",Thank you in advance.
const express = require('express');
const mysql = require('mysql');
const expressValidator = require('express-validator');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const flash = require('connect-flash');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/', routes);
app.set('view engine', 'pug');
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(__dirname + '/public'));
app.use(cookieParser('keyboard cat'));
const PORT = 4000
app.listen(PORT, function (err) {
if (err) console.log(err);
console.log("App started on PORT", PORT);
});
I have reorganized your codes. Please make sure your filte path declaration is correct.
var express=require('express');
var router = express.Router();
var controllers= require('../controllers/userController'); // if userController.js in controller folder.
router.get('/', controllers.homeController_index);
router.get('/signup', controllers.userController_signup);
router.post('/signup', controllers.userController_save);
router.get('/login', controllers.userController_login);
router.get('/dash', controllers.userController_dash);
module.exports = router;
userController.js
const userController_save = function (req, res, next) {
var name = req.body.name;
console.log(name);
}
app.js
const express = require('express');
const mysql = require('mysql');
const expressValidator = require('express-validator');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const flash = require('connect-flash');
const path = require("path");
const app = express();
const routes = require('./routes/root'); // If your root.js inside a routes folder
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.set('view engine', 'pug');
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(__dirname + '/public'));
app.use(cookieParser('keyboard cat'));
app.use('/', routes);
const PORT = 4000
app.listen(PORT, function (err) {
if (err) console.log(err);
console.log("App started on PORT", PORT);
});
I'm building a server with Node and Express, using handlebars as views. My controller contains the system logic functions, which receive the request and response objects as parameters and my Route, only makes the connection between the route and the controller. But I am not able to see the error to generate this error in the title.
My controller.js:
const router = express.Router();
exports.home = (req, res) => {
res.render('home', { entries: entries });
};
exports.Form = (req, res) =>{
res.render('form')
};
exports.FormFetch = (req, res) =>{
res.render('form-fetch')
};
My app.js:
const express = require('express');
const handlebars = require('express-handlebars');
const app = express();
app.engine('.hbs', handlebars.engine({
defaultLayout: 'main',
extname: '.hbs',
}));
app.set('view engine', '.hbs')
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
var userRoute = require('./routes')
app.get('/', userRoute)
app.use('/new-entry', userRoute)
app.use('/new-entry-fetch', userRoute)
app.listen(3000, () =>{
console.log('Ok')
});
My routes.js:
const express = require('express');
const controller = require('./controllers/controllers');
const app = express();
const entries = [];
app.get('/', (req, res) => {
res.render(controller.home, { entries: entries });
});
app.get('/new-entry', (req, res) => {
res.render(controller.Form);
});
app.get('/new-entry-fetch', (req, res) => {
res.render(controller.FormFetch);
});
app.post('/new-entry', (req, res) => {
entries.push({
title: req.body.title,
content: req.body.body,
published: new Date()
});
res.redirect(303, '/');
});
module.exports = app
Everyone I'm beginner in NODEJS I'm trying to do small chat app.I'm facing routing problem in user.js.
throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
^
TypeError: Router.use() requires a middleware function but got a undefined
I have this code in my user.js
const { Router } = require('express');
const router = Router();
const UserC = require('../controllers/userControllers.js');
router.get('/users', UserC.getUsers);
router.post('/users', UserC.crreateUsers);
router.get('/users/:id', UserC.getUser);
module.exports = {
routes: router
}
class index.js
const app = require('./app');
const confit = require('../config');
const userRoutes = require('./routes/user-router');
const rolesRoutes = require('./routes/roles-router.js');
const loginRoutes = require('./routes/login-router');
const takerServicios = require('./routes/takerServices-router');
const clienteAbogado = require('./routes/clienteAbogado-router');
const services = require('./routes/servicios-router');
app.use('/api', userRoutes.routes);
app.use('/api', rolesRoutes.routes);
app.use('/api', loginRoutes.routes);
app.use('/api', takerServicios.routes);
app.use('/api', clienteAbogado.routes);
app.use('/api', services.routes);
app.listen(app.get('port') );
app.use((err, req, res, next) => {
console.log(err);
res.status(err.status || 500).send(err.stack);
});
//console.log("hola servidor: ", app.get('port'));
class app.js
const express = require('express');
const morgan = require('morgan');
const exphbs = require('express-handlebars');
const helmet = require('helmet');
const path = require('path');
const bodyParser = require('body-parser');
const db = require('../conection');
const cors = require('cors');
const multer = require('multer');
const admin = require('firebase-admin');
const serviceAccount = require('../serviceAccountKey');
const app = express();
// ------------------------------- INICIALIZAR FIREBASE ADMIN ------------------------
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
})
const upload = multer({
storage: multer.memoryStorage()
})
// ------------------------------- settings ------------------------------------------
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.engine('.hbs', exphbs({
defaultLayout: 'main',
extname: '.hbs'
}));
app.set('view engine', '.hbs');
// ---------------------------------------------------------------- middlewares ----------------------------------------------------------------
app.use(morgan('dev'));
app.use(express.json());
app.use(express.urlencoded({
extended: true
}));
app.use(cors());
app.disable('x-powerd-by');
//app.use(bodyParser.json());
//app.use(bodyParser.urlencoded({extended:true}));
// ---------------------------------------------------------------- routes ----------------------------------------------------------------
app.use(require('./routes/index'));
// ---------------------------------------------------------------- static files ----------------------------------------------------------------
app.get('/style.css', function(req, res) {
res.sendFile(__dirname + "/" + "style.css");
});
app.use(express.static(path.join(__dirname,"public")));
//app.use(express.static(path.join(__dirname, 'public')));
dbConnection = async () => {
try {
await db.connect();
console.log('database online');
} catch(err) {
throw new Error(err);
}
}
module.exports = app;
In which line it crashes?
Indeed, the userControllers.js would be helpfully.
Maybe there is a typo?
router.post('/users', UserC.crreateUsers);
instead of
router.post('/users', UserC.createUsers);
For correctness, i would change the post route to singular: "createUser"
I think you just create one user with a single post.
BR
Patrick
I am getting the above error when running the following code in my express app. When I go to localhost:3000/cards.
This is in my cards.js file.
const express = require('express');
const router = express.Router();
const { data } = require('../data/flashcardData.json');
const { cards } = data;
router.get('/', (req, res) => {
res.render('card', {
prompt: cards[0].question,
hint: cards[0].hint
});
});
module.exports = router;
This is the code in my app.js file.
const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.set('view engine', 'pug');
const mainRoutes = require('./routes');
const cardRoutes = require('./routes/cards');
app.use(mainRoutes);
app.use('/cards', cardRoutes);
app.use((req, res, next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use((err, req, res, next) => {
res.locals.error = err;
res.status(err.status);
res.render('error');
});
app.listen(3000, () => {
console.log('The application is running on localhost:3000!');
});
Any help would be appreciated. Basically, I am trying to incorporate a json file into the express app and it is coming up with this error.
Set a default status in your error handler middleware if error does not contain the property status.
const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.set('view engine', 'pug');
const mainRoutes = require('./routes');
const cardRoutes = require('./routes/cards');
app.use(mainRoutes);
app.use('/cards', cardRoutes);
app.use((req, res, next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use((err, req, res, next) => {
res.locals.error = err;
const status = err.status || 500;
res.status(status);
res.render('error');
});
app.listen(3000, () => {
console.log('The application is running on localhost:3000!');
});
Im learning nodejs and I'm creating a server to get the price of cryptocurrencies using a npm called Coin-Ticker. I want to use the data I'm getting in an Angular app but it's not displaying the data in the html. This is my code:
server.js
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
const coinTicker = require('coin-ticker');
const api = require('./server/routes/api');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'dist')));
app.use('/api', api);
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
const port = process.env.PORT || '3000';
app.set('port', port);
const server = http.createServer(app);
server.listen(port, () => console.log(`API running on localhost:${port}`));
API.JS
const express = require('express');
const router = express.Router();
const coinTicker = require('coin-ticker');
/* GET api listing. */
router.get('/', (req, res) => {
res.send('api works');
});
router.get((req, res) => {
coinTicker('bitfinex', 'BTC_USD')
.then(posts => {
res.status(200).json(posts.data);
})
.catch(error => {
res.status(500).send(error)
});
});
module.exports = router;
Thanks for your help!
It is because coin ticker returns the json in the then so when you are doing res.status(200).json(posts.data); it is returning undefined. just replace that with res.status(200).json(posts) and it should work
Also you can not do router.get((req, res) => {
you need a path before this. I tried this code with
router.get('/convert', (req, res) => { and with the changes above it worked