Cannot access 'app' before initialization [VS code javascript webdev] - node.js

This is my server file called app.js and everytime I run node app.js, it gives me an error, "Cannot access 'app' before initialization" Can anyone help me understand why and how I can fix this? Here is my code:
require('dotenv').config();
const path = require('path');
const express = require('express'); // import express package
const app = express();
const homeRouter = require('./routes/home'); //refers to the home.js file in routes
const errorRouter = require('./routes/404'); //refers to the 404.js file in routes
const PORT = process.env.PORT || 3000;
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use('/', (request, response, next) => {
response.send("<h1> Welcome to my Project </h1>");
next();
});
app.use(express.static(path.join(__dirname, 'public')));
app.use(homeRouter);
app.use(errorRouter);
app.listen(PORT);

This code looks fine. Check refering app in router files or share those files so that I can give a look.
Btw, your middleware sending response, so if your router calls res.send or anything like that will cause an error.

Related

Why is Express isn't able to find ejs in netlify lambda serverless

I am trying to deploy a project with using serverless http with netlify. So far I have gotten the deployment to be successful, but the page says "Internal server error" and when I check the console, it says "Cannot find module ejs". I have tried to reinstall ejs and express even globally and have moved the "node_modules" folder a level above, but still no luck.
Here is my code:
require('dotenv').config()
const express = require('express')
const app = express()
const port = 3000;
const bodyParser = require('body-parser')
const router = require('./routes')
const path = require('path')
const ejs = require('ejs');
const serverless = require('serverless-http');
app.use(express.static(path.join(__dirname, "/public")))
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())
app.use('/.netlify/functions/index', router)
app.set('view engine', 'ejs')
module.exports.handler = serverless(app);
So I put app.set('view engine', 'ejs') and it says that it cannot find ejs
However, this does work on normal
node index.js
but I don't know why it isn't working here.
Help would be appreciated, thank You so much!!!
You forget to say where the folder for the views exist
This should fix it
// view engine setup
app.set('views', path.join(__dirname, 'views')); \\ views being the name of the folder in the root dir
app.set('view engine', 'ejs');

not getting file while routing

I am getting an error while routing file as Error: file not found
File structure
Controller
--orgaizationController
--blogesController
--pagesController
Views
--organization.ejs
--bloges.ejs
--pages.ejs
--index.ejs
organizationController.js
const express = require('express');
const router = express.Router();
router.get('/',async (req,res) => {
res.render('index');
});
router.get('/addedOrganization', async (req,res) => {
res.render('addedOrganization' , {});
});
server.js
const blogsController = require('./Controllers/campaignController');
const organizationController = require('./Controllers/campaignController');
const pagesController = require('./Controllers/campaignController');
app.use('/', organizationController)
app.use('/', blogsController)
app.use('/', pagesController)
Image
But when I change app.use('/', organizationController) to app.use('/organiztion', organizationController) I get the index page i.e my homepage
Please anyone help?
You need to set this middleware to render views without mentioning the path
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

Setting up MEAN stack not rendering app-root

I'm trying to setup a basic mean stack by following this guide, but the client doesn't seem to render the app instead the body contains,
<body>
<app-root></app-root>
</body>
The file structure is exactly the same as a blank angular cli project except the addition of two extra files.
PLUS: npm install --save ejs cors express body-parser
routes/index.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('index.html');
});
module.exports = router;
server.js
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var cors = require('cors')
var index = require('./routes/index');
// app
var app = express();
// cors
app.use(cors());
// views
app.set('views', path.join(__dirname, 'src'));
// engine
app.set('view enginer', 'ejs');
app.engine('html', require('ejs').renderFile);
// angular dist
app.use(express.static(__dirname + '/dist'));
// body bodyParser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
// route
app.use('/', index);
// Initialize the app.
var server = app.listen(process.env.PORT || 3000, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
I run an ng build and node server.js but get a blank white page in the browser.
Perhaps there is a breaking change that I'm not aware of since that guide was using angular2 (I'm using angular 6).
Since your index.html isn't directly inside the dist folder (rather, it is inside a sub-folder for some reason), try changing app.use(express.static(__dirname + '/dist')); to app.use(express.static(__dirname + '/dist/<your project name here>'));

Express server deployed, not work in openshiftapps but works fine in local

I just deployed my express.js server on openshiftapps and for some reason, one of the routes not working and I get :
Internal Server Error
Same route is fine in local.this route is my root route which only should render my index.ejs file. the other routes working just fine. I share the codes here, I hope you guys can help to see where did I do wrong.
So this is my server.js code :
var express= require('express');
var path = require('path');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var accountname = require('./routes/accountname');
var app = express();
//View Engine (We Use ejs)
app.set('views', path.join(__dirname,'views'));
app.set('view engine', 'ejs');
// app.use(express.static(path.join(__dirname,'edaccounting')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/', index);
app.use('/api/v1/', accountname);
app.listen(8080, function(){
console.log('Server is Started on port 8080');
})
And this is my index.js :
var express= require('express');
var router = express.Router();
router.get('/',function(req,res,next){
res.render('INDEX');
})
module.exports = router;
so for this route : app.use('/', index); I get Internal server error on the real server but it's working in my local and render the .ejs file. Other route is fine in real server. I used openshiftapps and I build my node.js app there with no errors!

The generated NodeJS Express application doesnt have "listen"?

When running express, the generated app.js is the following: (at the date of this post)
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use(function(req, res, next) {
...
});
if (app.get('env') === 'development') {
...
}
app.use(function(err, req, res, next) {
...
});
module.exports = app;
For simplicity I removed comments.
My question is really simple:
I've seen a lot nodeJS examples in websites, blogs, and docs, where they use one of the followings:
require('http').createServer(app).listen(3000);
or
app.listen(3000);
If I execute my generated express app (npm start), it runs. I can navigate to localhost:3000 with a browser and it is being served. So... how relevant is to use listen(port)?
Im asking this because I like to have full control of things.
Also, some examples of modules use listen, eg. module Sequelize
Article: "Usage with Express.JS",
link: http://sequelizejs.com/articles/express,
app.js
------
db
.sequelize
.sync({ force: true })
.complete(function(err) {
if (err) {
throw err[0]
} else {
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'))
})
}
})
This makes me think that I should sync before starting listening.
If I dont use listen, and let it listen automagically (as the generated code does), will I get troubles because of syncing and listening at the same time?
If you look at the package.json file you'll probably find its running /bin/www or some such startup script. That will have the "missing" listen statement.

Resources