ReferenceError: Cannot access 'app' before initialization - node.js

I have this Problem when I start my Backend, I want to test the post request in Postmann but I have this error, how can I fix it?
this is my Server . j s

const app = express() Should come before your middlewares... app.use(...)
Also make sure to connect your mongo database before your app initialization not after app.listen(...). Your application should depend on your database, throw error if database didn't connect, all this should happen in try{}catch(){}

The app variable is used before you declare it. Move your const app = express(); upward. Like this:
const express = require('express');
const app = express();

You are calling app.use methods before initializing app.
Just move const app = express() before app.use.

Related

How to manage NodeJs app code to reduce clutter

Hie,
I am developing a Nodejs (Express) web app and pretty much new to this technology. So far I see that there can only be one point of entry mine being my the server.js file. Now it seems all requests and/or processes should be initiated here which is fine for a smaller application, but my site has about 25 page routes already all of who's request should be handle here. I also have a dozen or so Ajax requests are handled here. Now even though I am processing different functions e.g CRUD operations in separate files, I still fear at some point my code will become unreadable as the server.js file get longer
const express = require("express")
const path = require("path")
const exphbs = require("express-handlebars")
let app = express()
app.set("views",path.join(__dirname,'templates'))
app.engine('handlebars',exphbs({defaultLayout:'main'}))
app.set('view engine','handlebars')
app.set('port',(process.env.PORT || 3000));
app.get('/',(req,res)=>{
res.render('home',{'title':'Home'});
});
app.get('/home',(req,res)=>{
res.render('home',{'title':'Home'});
});
app.get('/register',(req,res)=>{
res.render('register',{'title':'Register'});
});
app.use(express.static(path.join(__dirname, '/public')));
app.listen(app.get('port'),()=>{
console.log(`Server started on port : ${app.get('port')}`)
})
So far my server.js is this small, but it just hit me that I have 25 pages and multiple Ajax processes on each.
Yes, you have to structure your routes. For that, you have to look at Express Router. You have to create different route files based on a specific resource.
/routes/homeRoutes.js
const express = require("express");
const router = express.Router();
router.get('/',(req,res)=>{
res.render('home',{'title':'Home'});
});
module.exports = router;
server.js
const homeRoutes = require("./routes/homeRoutes");
app.use("/api/v1/home", homeRoutes);
Also, have a look at the following links for a better understanding of project structure and express router.
https://expressjs.com/en/guide/routing.html
project structure
I think what you are looking for is splitting the code up in local modules. You can place parts of your code in separate files, include module.exports at the end and then require(./filename.js) them in your server.js.
You can see an example here: https://www.tutorialsteacher.com/nodejs/nodejs-local-modules

why is my express API not responding?

Background
I am testing a simple Hello World app using NodeJs v7 and express in cloud9.
I am trying to make my example work but I am failing.
Problem
All my cloud9 configurations are fine so that is not the problem. The problem is my app. When i debug, the route "api/v1/HolaBananas" never gets called and I don't know why!
Even worst, when i make the request, the browser just hangs, like it is waiting for an answer from the server that will never come!
Code
The index.js has the initialization and launch code. It is important for me that I keep this separate from api.js for modular reasons.
index.js
"use strict";
const express = require("express");
const app = express();
app.use("/api/v1", require("./api.js"));
app.listen(process.env.PORT);
console.log(`Server listening on port ${process.env.PORT}!`);
The api.js simply contains the routes and what they are supposed to do.
api.js
"use strict";
const express = require("express");
module.exports = function() {
const api = express.Router();
api.get("/HolaBananas", function(req, res){
res.send("hello bananas!");
});
return api;
};
Question
I am sure I am not using api.get in the right way, but I truly want to separate my initialization and launch code from the api.
How can I fix my code so it works?
Note
I am following the course
https://www.edx.org/course/introduction-mongodb-using-mean-stack-mongodbx-m101x-0
You can fix it by two following ways
var api = require("./api.js")();
app.use("/api/v1", require("./api.js"));
as API.js return a function reference. so you need to call that function to access route.
Or You need to modify your api.js as follows if you don't want to change index.js
"use strict";
const express = require("express");
const api = express.Router();
api.get("/HolaBananas", function(req, res){
res.send("hello bananas!");
});
module.exports = api;
Solution
While Vikash Sharma's solution would work, I figured it out by following the recommendation of Jayant Patil and to read this other question:
https://codereview.stackexchange.com/questions/51614/exporting-routes-in-node-js-express-4
Turns out we had the same issue, but the given answer to that question also allows me to encapsulate the api file completely inside a function, preserving its scope.
Still, kudos++ for trying!
There is one subtle thing about it: You have to invoke the function that you export in your api.js and use the router object that is returned from that function, so here is what you should do:
You have to replace this line:
app.use("/api/v1", require("./api.js"));
with this:
app.use("/api/v1", require("./api.js")());

Unable to understand the Express server concept using Node.js

I was referring to some online tutorials for establishing a Node server using Express 4. I will make my question very simple and easy to understand.
The main app.js file has the following lines (other code lines like middlewares etc. are not show here)
var express = require('express');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
app.use('/', routes);
app.use('/users', users);
I have tested the above code. Included the index.js and users.js inside the routes folder. This worked perfect. This means that the http server is already created.
But, my confusion raised, when I say another type of coding done in another site. It has the following lines of code.
var express = require('express'),
routes = require('./routes'),
http =require('http’);
var app = express();
My first confusion is, why do we need to use the http middleware.
The code further creates a server like this
var server = http.createServer(app);
Since, I am using the Express framework, why do we need to create the server, this way
Reference can be found here https://github.com/azat-co/practicalnode/blob/master/ch5/blog-express/app.js#L72
Any help would be highly appreciated. Thanks in advance.
Perhaps the developer wanted to create a raw http server for some other specific use later on? Strictly speaking, it is not necessary to do that.
The following is perfectly sufficient to create an http server and begin listening for connections using express:
var express = require('express');
app = express();
app.listen(3000);
in express best way is:
app = express();
app.listen(3000);
in theory this:
var server = http.createServer(app);
could be used to reuse http server, for example to run sockets.
But app.listen also return http server like http.createServer(app);
We can do:
var server = http.createServer(app);
var io = require('socket.io')(server);
But we also can:
var server = app.listen(3033);
var io = require('socket.io')(server);
When createServer(app) may be useful? if we want listen to http i https:
http.createServer(app).listen(80);
https.createServer(options, app).listen(443);

Link one express js application to another

I have two Express JS application and I want to add a route for one inside the other so when this link is requested it goes to the sub-application. Is that possible??
Example:
The main application is accessed through the link www.linktoapp.com and it is written in Express js.
Now I have developed another Express js application and I want to access it through the link www.linktoapp.com/secondapp
My question is can I add this route (/sceondapp) in the main application so I can access it like I said?
Thanks.
You could always have two separate express processes running on 2 ports and then reverse proxy the requests.
https://github.com/nodejitsu/node-http-proxy
Your question is a bit confusing! What I understand from your question:
You have two expressjs application running. Two application can't run on same port. Two application can however run on two different ports. See example below.
var express = require("express");
var app1 = express(); //created the first app
var app2 = express(); //created the second app
app1.get("/",function(req,res){
res.send("<html><body><a href='/sec'>go second app</a></body></html>");
// created a link to app2
});
app1.get("/sec",function(req,res){ // redirection to second app
res.redirect("http://localhost:3001/");
})
app2.get("/",function(req,res){
res.send("welcome to second app");
});
app2.listen(3001,function(){ // app2 is listening on port 3001
console.log("app two is listening on 30001 ")
});
app1.listen(3000,function(){ // app2 is listening on 3000
console.log("app1 is listening on 3000");
});
What you want is to create an Express sub-app. Express sub-apps share routes, views, sessions, etc with the main app.
For example, let's say you want one node app, s_app.js, to be a sub-app of another, p_app.js.
s_app.js
var express = require('express');
var app = module.express = express();
// set routes for userjs
app.get('/path_1', function(req, res){
// display path_1
});
p_app.js
var express = require('express');
var app = express();
var s_app = require('s_app'); // mount s_app.js
app.use(s_app);
// now p_app and s_app share routes, views, sessions, etc
If you want more detail, take a look at a tutorial I wrote on how to build node.js sub-apps

Create ExpressJS Route Without Registering The Routing Module

In ExpressJS, you register the routing module like this:
app.use(app.router);
And you create a route like this:
app.get('/user/:id', function(req, res){
...
});
The problem is, if you create a route before you register the routing module then it is registered for you immediately.
For me, this is a problem because I'm building an NPM module that creates a route for itself. Right now, it has the unfortunate side-effect of registering the routing module without the user's knowledge. So if they happen to require my module before they register the static file handler, then it wrecks everything.
So my question is, how can I register a route without automatically registering the routing module?
I imagine your module requires the user to pass in their app, kind of like this:
module.exports = function(userApp) {
userApp.get(...);
...
}
Instead, make a new Express app and export that:
var express = require('express'),
app = express();
app.get(...);
...
module.exports = app;
And instead of having the user pass their app to you, have them use the app you export:
var express = require('express'),
yourModule = require('your-module'),
userApp = express();
userApp.use(express.static(...));
userApp.use(yourModule);

Resources