Node Express Js - node.js

I am working on Node Js and I am facing issue in my routes.js file and app.js file.
Routes file is no working.
App.js code
const express = require('express');
const app = express();
const routes = express.Router('./routes/routes');
const path = require('path');
const methodOverride = require('method-override');
const moment= require('moment');
app.locals.moment=moment;
app.locals.shortDateFormat="MM/DD/YYYY";
app.set('view engine', 'pug');
app.set('views', path.join(__dirname, 'index.jade'));
Route.js code
var express=require('express');
var routes= express.Router();
var controllers= require('../controllers');
// homepage routes
routes.get('/',controllers.homeController.index);

You need to export the routes from Route.js file
var express=require('express');
var routes= express.Router();
var controllers= require('../controllers');
// homepage routes
routes.get('/',controllers.homeController.index);
module.exports = routes
and in app.js
app.use('/', routes)

Related

failed to look up views

Here is my structure like
app.js
routes
index.js
views
partials
index.ejs
This is index.js in routes folder that is rendering the template called index.ejs form views folder
const express = require('express');
const router = express.Router();
const expressLayouts = require('express-ejs-layouts');
const path = require('path');
router.get('/', (req, res) => {
res.render(path.join(__dirname, '../index'));
})
module.exports = router;
Error says Failed to lookup view "layout" in views directory
You have to set the views directory first in app.js:
const express = require("express");
const app = express();
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
router.get('/', (req, res) => {
res.render('index.ejs'));
})

Browser keeps "waiting for localhost"

in my index.js file:
const express = require('express');
const router = express.Router();
// Do work here
router.get('/', (req, res) => {
res.send('Hey! It works!');
});
module.exports = router;
I am able to make the first request just fine, but every subsequent request just waits for localhost until it times out.
app.js looks like:
const express = require('express');
const session = require('express-session');
const mongoose = require('mongoose');
const MongoStore = require('connect-mongo')(session);
const path = require('path');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const passport = require('passport');
const promisify = require('es6-promisify');
const flash = require('connect-flash');
const expressValidator = require('express-validator');
const routes = require('./routes/index');
const helpers = require('./helpers');
const errorHandlers = require('./handlers/errorHandlers');
// create our Express app
const app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views')); // this is the folder where we keep our pug files
app.set('view engine', 'pug'); // we use the engine pug, mustache or EJS work great too
// serves up static files from the public folder. Anything in public/ will just be served up as the file it is
app.use(express.static(path.join(__dirname, 'public')));
// done! we export it so we can start the site in start.js
module.exports = app;
the start.js file looks like this. I should add that this is not my own code - it's part of the node.js tutorial from Wes Bos.
const mongoose = require('mongoose');
// import environmental variables from our variables.env file
require('dotenv').config({ path: 'variables.env' });
// Connect to our Database and handle any bad connections
mongoose.connect(process.env.DATABASE);
mongoose.Promise = global.Promise; // Tell Mongoose to use ES6 promises
mongoose.connection.on('error', (err) => {
console.error(`🙅 🚫 🙅 🚫 🙅 🚫 🙅 🚫 → ${err.message}`);
});
// READY?! Let's go!
// Start our app!
const app = require('./app');
app.set('port', process.env.PORT || 7777);
const server = app.listen(app.get('port'), () => {
console.log(`Express running → PORT ${server.address().port}`);
});
Managed to solve my own problem, so I'm reporting back for anyone who may have encountered the same issue coming from the Wes Bos Node.js tutorial.
The solution was to double check my variables.env file - I had stupidly left arrow brackets around the username and password fields. If you're having this issue, make sure your DATABASE environment variable looks something like this:
DATABASE=mongodb://dang:dang#ds057833.mlab.com:57833/dang-thats-delicious

router redirect in express not working

I have 3 files
app
routes/index.js
routes/home.js
app.js
var express = require('express');
var app = express();
//require routes
var index = require('./routes/index.js')
var home = require('./routes/home.js')
app.set('port',3000)
app.set('view engine', 'pug')
app.use('/', index);
app.use('/home' , home);
//app.use('/routes',users);
app.listen(3000);
module.exports = app;
index.js
var express = require('express');
var router = express.Router();
router.get('/' , function(req,res){
res.redirect('/home')
})
module.exports = router;
home.js
var express = require('express');
var router = express.Router();
router.get('/home' , function(req ,res){
res.send('Got request on home route')
})
module.exports = router;
This sends a cannot GET on HOME route.Strangely this works if i put both routes in one file.I think I am making a mistake while importing?

Added socket.io to back-end, it broke everything

Well, as the title suggests, I broke everything using socket.io. Mainly because the way it calls express breaks everything else using express.
Here is my old way of doing it:
/*jshint esversion: 6*/
const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
const path = require('path');
const expressValidator = require('express-validator');
const flash = require('connect-flash');
const session = require('express-session');
const passport = require('passport');
const fs = require('fs');
const db = require('./config/db');
// Init App
app = express();
// View Engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Bodyparser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false,
}));
// Set Static path
app.use(express.static(path.join(__dirname, 'static')));
Which works wonders! It works, however adding socket.io like so:
/*jshint esversion: 6*/
const app = require('express')();
const http = require('http').Server(app);
const socket = require('socket.io')(http);
const bodyParser = require('body-parser');
const path = require('path');
const expressValidator = require('express-validator');
const flash = require('connect-flash');
const session = require('express-session');
const passport = require('passport');
const fs = require('fs');
const db = require('./config/db');
// Init App
// app = express();
// View Engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Bodyparser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false,
}));
// Set Static path
app.use(express.static(path.join(__dirname, 'static')));
Breaks everything using express.* because it is saying express is not defined. So my static path gets broken and of course the app crashes.I tried several solutions, but to no avail.
Oops forgot to add the error:
app.use(express.static(path.join(__dirname, 'static')));
^
ReferenceError: express is not defined
Try this. The idea is that you need to import express. Socket.io can be required once the rest is defined.
/*jshint esversion: 6*/
const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
const path = require('path');
const expressValidator = require('express-validator');
const flash = require('connect-flash');
const session = require('express-session');
const passport = require('passport');
const fs = require('fs');
const db = require('./config/db');
// Init App
const app = express();
// Init http server
const server = http.createServer(app);
// Init socket
const socket = require('socket.io').listen(server);
// View Engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Bodyparser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false,
}));
// Set Static path
app.use(express.static(path.join(__dirname, 'static')));

Express.js - export/access function within route file

I am trying to export function within route file. Here is my code
app.js file
var express = require('express');
var bodyParser = require('body-parser');
var users = require('./routes/users');
var others=require('./routes/others')
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/others', others);
app.use('/users', users);
module.exports = app;
others.js file
var express = require('express');
var router = express.Router();
router.post("/test", function (req, res, next) {
res.send("success");
});
//Here i want to export function to users js file
var funDef=function(){
console.log("export a function")
}
moudle.exports=router;
How can I export or call funDef in users.js file. I tried the following way but it is not working
users.js file
var express = require('express');
var router = express.Router();
var readFun= require("./others.js");
router.post("/testUsers", function (req, res, next) {
res.send("suceess");
});
//getting undefined
readFun.funDef();
module.exports=router;
Can anyone guide me?
Try for the following:
function router() {}
router.prototype.funDef=function(){
console.log("export a function")
}
moudle.exports.router=router;
Another file:
var router = require('router').router;
var Router = new router();
Router.funDef();
EDIT:
// module.js
'use strict';
var temp = "this is a test";
module.exports.func = function() {
return temp;
}
// app.js
'use strict';
var module = require('./module');
console.log(module.func());

Resources