Cannot find module express - javascript

Im trying to run an express application and im getting the following error:
module.js:471
throw err;
^
Error: Cannot find module './controllers'
this is my app.js:
const express = require('express');
//let passport = require('passport');
//let session = require('express-session');
const app = express();
app.use(express.static(__dirname + '/public'));
app.use(express.json());
app.use(express.urlencoded({extended:false}));
app.get('/', (req, res) => {
res.redirect('index.html');
});
app.post('/', (req, res) => {
})
app.use('/',require('./controllers'));
/*
app.use(express.session({ secret: 'keyboard cat' }));
app.use(passport.initialize());
app.use(passport.session());
*/
app.listen(3000);
I would like to know why im getting this error
this is my application structure:

When you require a directory like this:
app.use('/', require('./controllers'));
...you are technically looking for ./controllers/index.js:
You would have to add the file name, for example:
app.use('/', require('./controllers/route'));

Related

Conditionally serve ejs and react.js builds in smae url

I want to serve ejs and react.js conditionally to the user. When the user visits the page he would be landed to a login page which would be served from ejs. Once he logins in successfully which would be through an OAUTH, I want to serve the react.js build of the app.
const path = require("path");
const express = require("express");
const app = express(); // create express app
let ejs = require('ejs');
// app.get('/login', (req, res) =\> {
// app.set("view engine", "ejs");
// res.render('index');
// });
app.use('/', express.static(path.join(\__dirname, "..", "build"))); //React.js prod build path
app.use('/', express.static("public"));
app.get('\*', (req, res) =\> {
if(true) {
app.set("view engine", "ejs");
res.render('index');
} else {
res.sendFile("index.html", { root: path.join(\__dirname, "..", "build") });
}
});
// start express server on port 3000
app.listen(3000, () =\> {
console.log("server started on port 3000");
});
Any help regarding the serving of both apps would be highly appreciated.

app.get() is not working. related to Difference between app.use and app.get in express.js

var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
module.exports = app;
I created express-generator. Then I tried to change app.use('/', indexRouter) → app.get('/', indexRouter) and app.use('/users', usersRouter) → app.get('/users', usersRouter).
Then app.get('/', indexRouter) was working(can hit the URL and get the page information). But app.get('/users', usersRouter) was NOT working. This returned 404 (NotFoundError: Not Found).
I already read this questionDifference between app.use and app.get in express.js
But I couldn't understand
./routes/index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
./routes/users
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
app.use is designed for middlewares and app.get is designed for GET requests. Middlewares are functions that are called before the controller. You may have a middleware to check if the user is authenticate or not, and accept the user's request or deny it.
When you have app.use('/', indexRouter), the indexRouter will be called for all your requests on all your routes. It is like /*.
When you have app.use('/users', usersRouter), the usersRouter will be called for all your requests on all routes that start with /users. It is like /users*.
This is how you can do a GET request:
app.get('/users', (req, res) => res.status(200).send({
message: 'It works.',
}));

throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))

hey guys i know this has been asked before but i do not understand it ,,
so anyone help please
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;
const api = require('./server/routes/api');
const path = require('path');
app.use(express.static(path.join(__dirname, 'dist/todo')));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use('/api', api);
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/todo/index.html'));
})
app.listen(port, () => console.log('server started'));
the error i get when starting the server
throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))

Node.js server running and listening on Port 3000 but Localhost:3000 didn't send any data

So the server is running and listening to port 3000 which isn't being blocked
as far as I can tell, but when I try and load the page it hangs for a while before providing the following message:
"This page isn’t working
localhost didn’t send any data.
ERR_EMPTY_RESPONSE
I'm not sure why I can't get anything to pull through even when I adjust the get('/") homepage to render something simple. There also aren't any errors pulling through the terminal so I'm unsure how to diagnose the problem.
My app.js code:
const express = require('express');
const path = require('path');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const expressValidator = require('express-validator');
const flash = require('connect-flash');
const session = require('express-session');
mongoose.connect('mongodb://localhost/nodekb');
let db = mongoose.connection;
// Check connection
db.once('open', function(){
console.log('Connected to MongoDB');
});
// Check for DB errors
db.on('error', function(err){
console.log(err);
});
// Init App
const app = express();
// Bring in Models
let Article = require('./models/article');
// Load View Engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// Body Parser Middleware
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
// Set Public Folder
app.use(express.static(path.join(__dirname, 'public')));
// Express Session Middleware
app.use(session({
secret: 'keyboard cat',
resave: true,
saveUninitialized: true
}));
// Express Messages Middleware
app.use(require('connect-flash')());
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
// Express Validator Middleware
app.use(expressValidator);
// Home Route
app.get('/', function(req, res){
Article.find({}, function(err, articles){
if(err){
console.log(err);
} else {
res.render('index', {
title:'Articles',
articles: articles
});
}
});
});
// Route Files
let articles = require('./routes/articles');
let users = require('./routes/users');
app.use('/articles', articles);
app.use('/users', users);
app.listen(3000, function(){
console.log("We are running on port 3000");
});
I think the problem is your query is fetching empty array.
I have added condition in callback of query to check array length of articles.
app.get('/', function(req, res){
Article.find({}, function(err, articles){
if(err){
console.log(err);
res.json(err);
}else if(articles.length == 0){
console.log("Articles not found");
res.json({error : "Articles not found"});
} else {
console.log("Articles found");
res.render('index', {
title:'Articles',
articles: articles
});
}
});
});
I hope it will help you.

Nodejs and mongodb connection error after upgrading Mongo

Am trying to build some Todo app using Express and mongodb but i have some problems with nodejs and mongo connection and i searched about it on internet but didn't get any solution for my problem.
When trying to connect to mongodb from node js as in this code:
// This to require Express framework to use it
const express = require('express');
const csrf = require('csurf');
const errorhandler = require('errorhandler')
// Loads the piece of middleware for sessions
const logger = require('morgan');
const favicon = require('serve-favicon');
const methodOverride = require('method-override');
// This is a middleware to handle requests and parse the forms
const bodyParser = require('body-parser');
const routes = require('./routes');
const tasks = require('./routes/tasks');
const http = require('http');
const path = require('path');
const mongoskin = require('mongoskin');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const db = mongoskin.db("mongodb://localhost:27017/todo");
// Define object of express
const app = express();
app.use((req, res, next) => {
req.db = {};
req.db.tasks = db.collection('tasks');
next();
});
// This makes us can access app name from any JADe template
app.locals.appname = "Todo App Express.js";
app.locals.moment = require('moment');
// set app port to 8081 port
app.set('port', 8081);
// these tells express where's project safe templates in, and tell what's
// their extension will be.
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
// show express favicon in browser
app.use(favicon(path.join('public', 'favicon.ico')));
// this will print requests in terminal
app.use(logger('dev'));
// using body parser to can parse requests
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride());
// to use CSRF we need cookie parser
app.use(cookieParser('CEAF3FA4-F385-49AA-8FE4-54766A9874F1'));
app.use(session({
secret: '59B93087-78BC-4EB9-993A-A61FC844F6C9',
resave: true,
saveUninitialized: true
}));
app.use( csrf() );
// to process LESS stylesheets into CSS ones
app.use(require('less-middleware')(path.join(__dirname, 'public')));
// to use other static files which inside public
app.use(express.static(path.join(__dirname, '/public')));
// to make csrf used in templates
app.use( (req, res, next) => {
res.locals._csrf = req.csrfToken();
return next();
});
app.param('task_id', (req, res, next, taskId) => {
req.db.tasks.findById(taskId, (error, task) => {
if (error) return next(error);
if (!task) return next(new Error('Task is not found.'));
req.task = task;
return next();
});
});
// homepage to show our todo homepage
app.get('/', routes.index);
// list all created tasks [in-progress ones]
app.get('/tasks', tasks.list);
// this to mark all task as completed in one step
app.post('/tasks', tasks.markAllcompleted);
// this to add new task
app.post('/tasks', tasks.add);
// this to mark specfic task as completed
app.post('/tasks/:task_id', tasks.markcompleted);
// this to delete specfic task by :task_id
app.delete('/tasks/:task_id', tasks.del);
// this to list all completed tasks
app.get('/tasks/completed', tasks.completed);
// this 404 error page to show it if user requested any route doesn't exist in our routes
app.all('*', (req, res) => {
res.status(404).send();
});
if ('development' == app.get('env')) {
app.use(errorhandler());
}
// create our server
http.createServer(app).listen(app.get('port'),
() => {
console.log('Express server listening on port ' + app.get('port'));
});
I go this error in terminal:
/home/luffy/nodejs-train/todo-express-mongodb/node_modules/mongodb/lib/mongo_client.js:804
throw err;
^
TypeError: Cannot read property 'apply' of undefined
at EventEmitter.<anonymous> (/home/luffy/nodejs-train/todo-express-mongodb/node_modules/mongoskin/lib/collection.js:51:21)
at Object.onceWrapper (events.js:272:13)
at EventEmitter.emit (events.js:180:13)
at /home/luffy/nodejs-train/todo-express-mongodb/node_modules/mongoskin/lib/utils.js:134:27
at result (/home/luffy/nodejs-train/todo-express-mongodb/node_modules/mongodb/lib/utils.js:414:17)
at executeCallback (/home/luffy/nodejs-train/todo-express-mongodb/node_modules/mongodb/lib/utils.js:406:9)
at /home/luffy/nodejs-train/todo-express-mongodb/node_modules/mongodb/lib/mongo_client.js:271:5
at connectCallback (/home/luffy/nodejs-train/todo-express-mongodb/node_modules/mongodb/lib/mongo_client.js:940:5)
at /home/luffy/nodejs-train/todo-express-mongodb/node_modules/mongodb/lib/mongo_client.js:801:11
at process._tickCallback (internal/process/next_tick.js:112:11)
[nodemon] app crashed - waiting for file changes before starting...
And in my Firefox got :
Unable to connect
Firefox can’t establish a connection to the server at localhost:8081.
Using NodeJS V9.8.0 and mongodb v3.4.14
This was a problem even we faced and it seems it just has to do with the consequent versions of 'mongoskin'. Why don't you try and use mongodb ?
Saves time and a much better option!

Categories