node.js + express error: Cannot read property 'handle' of undefined - javascript

I am new to node.js. I was trying a script which is using express module.
I have installed express, using,
npn install express
When I run the code I got the error
TypeError: Cannot read property 'handle' of undefined
at Function.app.use (c:\node_modules\express\lib\application.js:113:9)
at Object.<anonymous> (c:\node\uploadResize.js:13:6)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:901:3
How to solve this issue?
Here is my node script.
var http = require('http'), // Libraries
util = require('util'),
fs = require('fs'),
couch = require('cradle'),
connect = require('express'),
endsWith, // Internal Functions
determineMimeType,
upload;
connect()
.use(connect.bodyParser())
.use(upload)
.listen(3000);
upload = function (req, res, next) {
// function body
}

You need to assign upload a value before passing it to app.use

Use something like this:
var app = express();
app.configure(function() {
var hourMs = 1000*60*60;
app.use(express.static('c:\\node', { maxAge: hourMs }));
app.use(express.directory('c:\\node'));
app.use(express.errorHandler());
});

the code not is npm install express ??
then the dir node_modules in the same dir in witch you have your app
C:\node\node_modules
C:\node\app.js

Related

Error: Cannot find module 'config' at Function.Module._resolveFilename

Hii I have simple node server, with the following structure
myapp
-config
-default-json
-index.js
-package-lock.json
-package.json
Here is my part of my index.js
'use strict';
const
config = require('config'),
express = require('express'),
request = require('request'),
body_parser = require('body-parser'),
app = express().use(body_parser.json()); // creates express http server
// Sets server port and logs message on success
app.listen(process.env.PORT || 1337, () => console.log('webhook is listening'));
when I run node index.js I get the following error
internal/modules/cjs/loader.js:583
throw err;
^
Error: Cannot find module 'config'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
at Function.Module._load (internal/modules/cjs/loader.js:507:25)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:22:18)
at Object.<anonymous> (C:\xampp\htdocs\chat\index.js:13:14)
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)
what is wrong with my code?
I found solution by by installing config from npm
https://www.npmjs.com/package/config
follow the instruction above and it should work , it might help some one in future
You have to explicitly add the config module in your package.json:
"dependencies": {
"config": "version number"
}
https://www.npmjs.com/package/config
It means there is no config.js in your current location. Put the exact location of the config.js file..
Try,
config = require('./config/config'),

Node.js async await in express

I'm building an endpoint /users which will return the contents in the Users.json file. I'm using aysnc/await feature.
var express = require('express');
var app = express();
var fs = require('fs');
var readFile = Promise.promisify(fs.readFile);
const util = require('util');
app.get('/users', async (req, res, next) => {
try {
const user = await readFile('./users.json');
return eval(user);
//res.send(JSON.parse(data));
// res.json(user);
} catch (e) {
//this will eventually be handled by your error handling middleware
next(e)
}
});
app.listen(3000,function(){
console.log("listening on port 3000");
});
This throws the below error
SyntaxError: Unexpected token (
at createScript (vm.js:56:10) at Object.runInThisContext (vm.js:97:10)
at Module._compile (module.js:542:28) at Object.Module._extensions..js
(module.js:579:10) at Module.load (module.js:487:32) at tryModuleLoad
(module.js:446:12) at Function.Module._load (module.js:438:3) at
Module.runMain (module.js:604:10) at run (bootstrap_node.js:389:7) at
startup (bootstrap_node.js:149:9)
I'm using the npm 3.10.10 with node v6.11.3.
Can someone please guide where I have gone wrong?
Async/await is only available in Node versions 8 an up. Try using a newer Node version if possible.
Instead of calling:
return eval(user);
You should call:
res.send(JSON.parse(user));
or
res.send(JSON.stringify(JSON.parse(user)));
and use bodyParser.json() middleware if returning an object.
Likewise in the catch block,
res.status(500).send(‘there was an error’);
and log the error to your console.
——-
Also, fs.readFile takes another param, the encoding. Use ‘utf-8’. It returns a buffer, not a string, if you leave it out.

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.

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

Trying to setup Node.js (Express) to work with vhosts, and getting unexpected errors

I'm trying to set it up to work with a couple vhosts, so that I could manage everything through the one node app; but I've been getting this error.
It's late right now, so my mind isn't 100%, but hopefully someone can see something I don't.
/vhosts/app.js:13
.listen(3000);
^
SyntaxError: Unexpected token ;
at Module._compile (module.js:437:25)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)
Here's the code:
var express = require('express');
var app = express();
app
.use(express.vhost('localhost', require('/first/vhost/app.js').app)
.use(express.vhost('localhost2', require('/second/vhost/app.js').app)
.listen(3000);
And that first vhost app runs fine, if I got and run it manually with node app.
As Brett points out you are missing the last bracket:
var express = require('express');
var app = express();
app
.use(express.vhost('localhost', require('/first/vhost/app.js').app))
.use(express.vhost('localhost2', require('/second/vhost/app.js').app))
.listen(3000);
You should not use require inside the the Connect middleware. This way it would also have been easier to spot :-)
var express = require('express');
var app = express();
var first = require('/first/vhost/app.js').app;
var second = require('/second/vhost/app.js').app;
app
.use(express.vhost('localhost', first))
.use(express.vhost('localhost2', second))
.listen(3000);

Categories

Resources