Node.js + Express give me error - Cannot GET / - javascript

I created a simple application. Until I split the application code into an MVC template, everything worked. Below I present the code of my application. After going to localhost:3000/add-service you will see Cannot Get /add-service message.
Where is the problem that I unfortunately cannot solve?
app.js
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const expressLayouts = require('express-ejs-layouts');
const adminRoutes = require('./Routes/admin');
const shopRouters = require('./Routes/shop');
const app = express();
app.use(expressLayouts);
app.set('view engine', 'ejs');
app.set('views', './views');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/add-service', adminRoutes);
app.use(shopRouters);
app.use('/', (req, res, next) => {
res.status(404).render('./pages/404', {
title: '404 Page Not Found',
path: '',
});
});
app.listen(3000);
admin.js - this is my router file
const express = require('express');
const router = express.Router();
const bikesController = require('../controllers/bikes');
router.get('/add-service', bikesController.getAddBike);
module.exports = router;
bikes.js - this is my controller
const bikes = [];
exports.getAddBike = (req, resno) => {
res.render('../views/pages/add-service', {
path: 'pages/add-service',
title: 'Add in Service',
});
};
exports.postAddBike = (req, res) => {
bikes.push({ title: req.body.bikeModel });
res.redirect('/');
};
exports.getBikes = (req, res) => {
res.render('./pages/shop', {
model: bikes,
docTitle: 'List of Bikes',
path: '/',
title: 'Main Page',
});
};
App Tree

app.use('/add-service', adminRoutes);
You've mounted adminRoutes at /add-service
router.get('/add-service', bikesController.getAddBike);
The only end point that service provides is /add-service
Combine them and you have the URL: /add-service/add-service, which isn't what you are asking for.
The point of the router is that it doesn't need to know about the URLs above where it sits.
The router should just be dealing with its own section of the URL hierarchy:
router.get('/', bikesController.getAddBike);

Related

Node/Express: TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type function ([Function (anonymous)])

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

TypeError: Router.use() requires a middleware function but got a undefined problem in routeer

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

Express: empty req.body

I have simply express server:
const express = require('express');
const exphbs = require('express-handlebars');
const path = require('path');
const bodyparser = require('body-parser');
const app = express();
const hbs = exphbs.create({
defaultLayout: 'main',
extname: 'hbs'
});
const _PORT = process.env.PORT || 80;
app.engine('hbs', hbs.engine);
app.set('view engine', 'hbs');
app.set('views', 'views');
app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json({ type: 'application/*+json' }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(require('./routers/login'));
serverStart();
async function serverStart(){
try{
app.listen(_PORT);
console.log('[SERVER] Server is listening port ' + _PORT + ' now.');
}catch(error){
console.log(error);
}
}
And simply router:
const { Router } = require('express');
const router = Router();
router.get('/', async (req, res) => {
res.render('login', {
title: 'main page'
});
});
router.post('/', async (req, res) => {
console.log(req.body);
});
module.exports = router;
Why 'req.body' is always empty?
I tried to send POST query from "Postman", but it isn't work.
It's working only with x-www-form-urlencoded query, but I want to send json query.
P.S. Sorry for my english.
UPD: postman screenshot
link
I've been try your code and it's working fine, you only have to change your code:
app.use(bodyparser.json({ type: 'application/*+json' }));
With this code below:
app.use(bodyparser.json({ type: 'application/json' }));
Note: If you're use the latest version of express, then you should not to install body-parser, Because body-parser is already included.
So, you can use this code below:
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
I hope it can help you.

express-ejs-layout using different layout

Im using express-ejs-layout for my project. my project has routing. I want use different layout for different res queries. for example if query is: www.xxx.com/a, use LayoutA.ejs, if query is: www.xxx.com/b, use LayoutB.ejs. My index.js part code is:
...
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, '/app_server/views'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(ejsLayout);
app.use('/public', express.static(path.join(__dirname, 'public')));
require('./app_server/routes/routeManager')(app);
...
how can I?
I've just solve problem myself. I'll write for friends who face to same problem.
app.get('/a', function(req, res) {
res.render('view', { layout: 'LayoutA' });
});
app.get('/b', function(req, res) {
res.render('view', { layout: 'LayoutB' });
});
This is what I do:
First, I set a default layout
// app.js
app.set('layout', 'layouts/front') // assuming it's inside the 'views' directory
Then, I use middlewares for separate Router instances:
// app.js
app.use('/admin', AdminRoutes);
In my AdminRoutes.js:
// AdminRoutes.js
const router = express.Router();
router.use((req, res, next) => {
// changing layout for my admin panel
req.app.set('layout', 'layouts/admin');
next();
});
router.get('/', (req, res) => {
res.render('admin/index'); // will use admin layout
});
const path = require('path')
const express = require('express');
const app = express();
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.set('layout', 'layoutsA', 'layoutsB');
const router = require("express").Router();
const expressLayouts = require("express-ejs-layouts");
// user router
router.use(expressLayouts)
router.get('/, (req, res) =>{
res.render("user", {layout: "layoutsA"})
})
const router = require("express").Router();
const expressLayouts = require("express-ejs-layouts");
// post router
router.use(expressLayouts)
router.get('/, (req, res) =>{
res.render("user", {layout: "layoutsB"})
})

Node.js browser error Cannot GET/

I'm quite new to Node, I've been following a tutorial to build a simple server that serves dynamic pags with some basic routes but keep getting the Error: Cannot GET/ after running node server.js and calling localhost:3300 on the browser. My routes are defined externally and initialized using a routes.initialise() as follows:
//routes.js
var home = require('../controllers/home'),
image = require('../controllers/image'),
express = require('express');
module.exports.initialize = function(app, router) {
//var router = express.Router();
router.get('/', home.index);
router.get('/images/:image_id', image.index);
router.post('/images', image.create);
router.post('/images/:image_id/like', image.like);
router.post('/images/:image_id/comment', image.comment);
app.use('/', router);
};
I've searched far and wide but no solution forthcoming. I'm really frustrated and will need some help here.
I have a server.js that creates the server:
//server.js
var express = require('express'),
config = require('./server/configure'),
app = express();
app.set('port', process.env.PORT || 3300);
app.set('views', __dirname + '/views');
app = config(app);
var server = app.listen(app.get('port'), function() {
console.log('Server up: http://localhost:' + app.get('port'));
});
and a configure.js that configures the server:
//configure.js
var path = require('path'),
routes = require('./routes'),
exphbs = require('express3-handlebars'),
express = require('express'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
morgan = require('morgan'),
methodOverride = require('method-override'),
errorHandler = require('errorhandler');
module.exports = function(app) {
app.engine('handlebars', exphbs.create({
defaultLayout: 'main',
layoutsDir: app.get('views') + '/layouts',
partialsDir: [app.get('views') + '/partials']
}).engine);
app.set('view engine', 'handlebars');
app.use(morgan('dev'));
app.use(bodyParser({
uploadDir:path.join(__dirname, 'public/upload/temp')
}));
app.use(methodOverride());
app.use(cookieParser('some-secret-value-here'));
routes.initialize(app, new express.Router());
app.use('/public/', express.static(path.join(__dirname, '../public')));
if ('development' === app.get('env')) {
app.use(errorHandler());
}
return app;
};
also two files, home.js and image.js which are supposed to provide the default routes from configure.js:
//home.js
module.exports = {
index: function(req, res) {
res.send('The home:index controller');
}
};
//image.js
module.exports = {
index: function(req, res) {
res.send('The image:index controller ' + req.params.image_id);
},
create: function(req, res) {
res.send('The image:create POST controller');
},
like: function(req, res) {
res.send('The image:like POST controller');
},
comment: function(req, res) {
res.send('The image:comment POST controller');
}
};
Anytime I try to GET any of the links on the browser it returns the Cannot GET/ error. Any help will be greatly appreciated.
Thank you so much :)
I actually copied your exact code and it worked as you expect, though frankly it's got a bunch of indirection and at least one deprecated module. Maybe you have a PORT environmental variable set, and so the app isn't actually running on 3300?

Categories