Cannot read property 'get' of undefined. Using nodejs on Cloud9 - javascript

If this helps at all: I am following the instructions in chapter 3 of Simon Holmes' book, "Getting MEAN with Mongo, Express, Angular, and Node".
I am in the beginning stages of separating my routes and controllers into separate files. When I bypass creating the variables and hard code require('express').Router().get('/', ctrlMain.index); and other combinations that have the same functionality, I get the same error. So, I have narrowed the problem down to the first line of index.js, although the error I am getting points to the GET method in line 6 of the same file. I have provided my index.js, main,js, app.js, files, as well as the full error message I'm getting below. I would be happy to provide any other parts of my project/file structure if this information isn't enough! Hopefully someone will be able to point me in the right direction.
This is my index.js file:
var express = require('express');
var router = express.Router();
var ctrlMain = require('../controllers/main');
/* GET home page. */
router.get('/', ctrlMain.index);
module.exports = router;
My main.js file:
/* GET home page */
module.exports.index = function(req, res) {
res.render('index', { title: 'Express' });
};
and my app.js file (not sure if this is helpful):
var express = require('express')
, routes = require('./app_server/routes/index')
, user = require('./app_server/routes/user')
, http = require('http')
, path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/app_server' + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Finally, here is the error I'm getting:
TypeError: Cannot read property 'use' of undefined
at Object.<anonymous> (/home/ubuntu/workspace/lab5/app_server/routes/index.js:6:7)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (/home/ubuntu/workspace/lab5/app.js:6:14)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)

Related

TypeError: app.use() requires a middleware function

Every time I try to run the app after add users routes it gives error something like this
C:\Users\adity\Desktop\thinkster\medium-api\node_modules\express\lib\application.js:210
throw new TypeError('app.use() requires a middleware function')
^
TypeError: app.use() requires a middleware function
at Function.use (C:\Users\adity\Desktop\thinkster\medium-api\node_modules\express\lib\application.js:210:11)
at Object.<anonymous> (C:\Users\adity\Desktop\thinkster\medium-api\app.js:15:5)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)
[nodemon] app crashed - waiting for file changes before starting...
This is my file Structure
app.js
const app = express();
app.use('./routes');
routes/index.js
const express = require('express');
const router = express.Router();
router.use('/api', require('./api'));
module.exports = router;
routes/api/index.js
const express = require('express');
const router = express.Router();
router.use('/', require('./users'));
module.exports = router;
routes/api/users.js
const express = require('express');
const router = express.Router();
router.get('/users', (req, res) => res.send('Hello world'));
module.exports = router;
I found a website called realworld.io and I am following there a way of making nodejs API and here I get stuck every time. And I can't find where the problem is.
The code app.use('./routes'); in your app.js is incorrect (there is only one string parameter, which violates the app.use() syntax).
To define "routes" correctly, the code would look like:
// app.js
const app = express();
const routes = require('./routes');
app.use('/', routes);

Cannot read property '_header' of undefined

The offending code is the app.use(express.static("web")) line.
var express = require('express')();
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
//app.get('/', function(res, req) {
// res.sendFile(__dirname + '/www/index.html');
//})
app.use(express.static("web"));
which returns the following error in console:
/Users/matthewwalker/CVLGBT/CVLGBT/www/node_modules/finalhandler/index.js:92
if (!err && res._header) {
^
TypeError: Cannot read property '_header' of undefined
at /Users/matthewwalker/CVLGBT/CVLGBT/www/node_modules/finalhandler/index.js:92:21
at Function.handle (/Users/matthewwalker/CVLGBT/CVLGBT/www/node_modules/express/lib/application.js:170:5)
at app (/Users/matthewwalker/CVLGBT/CVLGBT/www/node_modules/express/lib/express.js:38:9)
at Object.<anonymous> (/Users/matthewwalker/CVLGBT/CVLGBT/www/index.js:2:11)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
Other times when I change up the code slightly I get express is not defined. File structure: index.js and node modules under root, while all html/css/js/imgs are under /web. I'm not sure why this header flag is being thrown. When I use the app.get line, it only sends the html file but no images or js. I need to be able to serve the whole directory of /web.
You're constructing an app instance on the first line, and then calling it on line 2:
var express = require('express')();
var app = express();
You should do this instead:
var express = require('express');
var app = express();
Or this:
var app = require('express')();
You can find more information about the express api here.

How to import and export files in NodeJS?

https://hastebin.com/ipuyupuqop.js main JS file
https://hastebin.com/meninifuku.js JS file with issues
I've been working on an API, however, routing doesn't seem to work. I've overcome some issues with this, however, this is the issue that is most affecting me.
C:\Users\-----\WebstormProjects\BoR-CORE\routes\v1\account.js:3
let router = express.Router();
^
TypeError: Cannot read property 'Router' of undefined
at Object.<anonymous> (C:\Users\-----\WebstormProjects\BoR-CORE\routes\v1\account.js:3:22)
at Module._compile (module.js:660:30)
at Object.Module._extensions..js (module.js:671:10)
at Module.load (module.js:573:32)
at tryModuleLoad (module.js:513:12)
at Function.Module._load (module.js:505:3)
at Module.require (module.js:604:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (C:\Users\-----\WebstormProjects\BoR-CORE\app.js:17:15)
at Module._compile (module.js:660:30)
It seems to me that you are exporting wrong file. You need to export router and import this into app.js.
This should be like this:
//File router/index.js
const user = require('./user'),
error = require('./error'),
response = require('./response');
module.exports = function(app) {
app.get('/v1/details', user.checkUser, user.getDetails, response.sendResponse);
app.post('/v1/details', user.checkUser, user.insertDetails, response.sendResponse);
};
//Your `app.js`
"use strict";
//NPM Modules
const express = require('express'),
path = require('path'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
//Internal Modules
router = require('./router');
var app = express();
// configure the app to use bodyParser()
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
console.log('server listening at 127.0.0.1 over port 2318'.info);
app.use(cookieParser());
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
router(app);
let port = process.env.PORT || 8080;
app.listen(port);
you should export the router like module.exports = router;
I think the problem is in your second file.
Instead of requiring the main app to get the express object, simply require('express') itself.
I think it should work this way.

Nodejs - throw unpredictable error as `property 'get' of undefined`

I am trying to run my node app. But I am getting an error, which I am not able to understand. please any one help me to understand this?
here is my code :
var express = require("express"),
app = express(),
path = require("path");
app.get("/", function( req, res ) {
res.sendfile( path.join(__dirname + '/index.html'));
});
var adminRouter = express.Router();
adminRouter.get('/', function(req, res) {
res.send('I am the dashboard!');
});
app.use("/admin", adminRouter);
app.listen(process.env.PORT, process.env.IP);
console.log("basic app listeners!");
the error I am getting is :
adminRouter.get('/', function(req, res) {
^
TypeError: Cannot read property 'get' of undefined
at Object.<anonymous> (/home/ubuntu/workspace/server.js:16:12)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:990:3
Can any one help me? I am running my app in cloud9.
thanks in advance!!
Your express version less than +4 , probably version 3. Try
npm uninstall express --save
Then re-install.
adminRouter.get('/', function(req, res) {
res.send('I am the dashboard!');
});
try it like this as well.
adminRouter.route('/').get(function(req,res){
res.json({'hello there from main route!'});
});
Actually this is express version problem.
express.Router(); is supported on version 4.x and cloud 9 support by default 3.x
change your package.json
"express": "^4.15.2",
and delete node_module folder
then run
npm install

Calling helper function in node.js within callback?

I'm fairly new to programming with node.js and am not quite sure why I am getting this error. The function looks to be set up correctly, and I don't believe I have any asynchronous problems b/c those should be account with the self variable I put in place (I think). I did try w/o that too, using simple var consolePrint(...) Anyways, this is my code below and the error log below that.
/* global __dirname */
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var self = this;
//CALLING HELPER FUNCTION HERE
var server = app.listen(8000, self.consolePrint(server));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/public', express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/public/views/index.html');
});
//---------------helper function(s)-------------------//
self.consolePrint = function(serverVar){
var host = serverVar.address().address;
var port = serverVar.address().port;
console.log('Example app listening at http://%s:%s', host, port);
}
and error:
C:\Users\Daniel\Desktop\workspace\alarm_clock\index.js:17
var server = app.listen(8000, self.consolePrint(server));
^
TypeError: undefined is not a function
at Object.<anonymous> (C:\Users\Daniel\Desktop\workspace\alarm_clock\index.js:17:36)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
12 May 01:01:36 - [nodemon] app crashed - waiting for file changes before starting...
This will resolve the problem:
var server = app.listen(8000, function(){self.consolePrint(server)});
You are using the function before defining it. Put the listen function below the 'self.consolePrint' assignment statement or assign the before using it, it will work.

Categories

Resources