how to use connect-orientdb module with express - javascript

My goal is to connect my server code that its with nodejs and expressjs framework to my database that is with orientdb.
first of all i wanted to store my sessions in database. but i had difficulty connecting my server to database.
the error that i get when i execute server.js:
/Users/soroush/Desktop/nodeOrient/node_modules/connect-orientdb/lib/connect-orientdb.coffee:191
})(connect.session.Store);
^
TypeError: Cannot read property 'Store' of undefined
at module.exports (/Users/soroush/Desktop/nodeOrient/node_modules/connect-orientdb/lib/connect-orientdb.coffee:22:46)
at Object.<anonymous> (/Users/soroush/Desktop/nodeOrient/server.js:8:48)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Function.Module.runMain (module.js:575:10)
at startup (node.js:160:18)
at node.js:449:3
and my server.js code is:
var express = require('express'),
cs = require("coffee-script/register"),
app = express(),
path = require('path'),
cookieParser = require('cookie-parser'),
session = require('express-session'),
config = require('./config/config.js'),
orientDBStore = require('connect-orientdb')(session),
OrientDB = require('orientjs'),
orientDBConfig = {
server : {
host: "localhost",
port:2424
},
db : {
user_name: "admin",
user_password: "admin"
},
database : "sessions",
class_name : "sessions_class"
},
server = OrientDB({
hose : "localhost",
port : "2424",
username : "root",
password : "root"
})
;
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('hogan-express'));
app.set('view engine', 'html');
app.use(express.static(path.join(__dirname,'public' )));
app.use(cookieParser());
require('./routes/route.js')(express, app);
app.use(session({
secret:"mySecret",
store: new orientDBStore(orientDBConfig)
}));
app.listen(8000, function () {
console.log("app is listening on port 8000");
})
my main problem is that the connect-orientdb was used when the session module was builtin in express, but now that session is a different module i have occurred to this problem.

Check out this guide for ExpressJS in OrientDB: Blog Tutorial with ExpressJS and OrientDB.
And try to use:
orientDBStore = require('orient')(session),
instead of:
orientDBStore = require('connect-orientdb')(session),

Finally i found a solution for it if anyone faced this problem:
var session = require('express-session'),
OrientoStore = require('connect-oriento')(session);
app.use(session({
secret: 'SomeSecret',
store: new OrientoStore({
server: "host=localhost&port=2424&username=dev&password=dev&db=test"
})
}));
for more info this github link is useful.

Related

Node JS app shuts down after ten seconds in Production env but runs fine on local env

I have a Node JS app which serves as a backend for a React web app. The application when started serves the React app and handles all the API calls. I connect to a MySQL database for data fetch. The app runs normally on local environment but crashes when deployed on an Ubuntu server(on AWS). On server, the app starts normally but after few seconds it crashes.
This is the error it throws when started
Error connecting: Error: connect ETIMEDOUT
at PoolConnection.Connection._handleConnectTimeout (/home/ubuntu/localSystem/node_modules/mysql/lib/Connection.js:412:13)
at Object.onceWrapper (events.js:313:30)
at emitNone (events.js:106:13)
at Socket.emit (events.js:208:7)
at Socket._onTimeout (net.js:422:8)
at ontimeout (timers.js:498:11)
at tryOnTimeout (timers.js:323:5)
at Timer.listOnTimeout (timers.js:290:5)
--------------------
at Protocol._enqueue (/home/ubuntu/localSystem/node_modules/mysql/lib/protocol/Protocol.js:144:48)
at Protocol.handshake (/home/ubuntu/localSystem/node_modules/mysql/lib/protocol/Protocol.js:51:23)
at PoolConnection.connect (/home/ubuntu/localSystem/node_modules/mysql/lib/Connection.js:119:18)
at Pool.getConnection (/home/ubuntu/localSystem/node_modules/mysql/lib/Pool.js:48:16)
at Object.<anonymous> (/home/ubuntu/localSystem/model/db.js:29:12)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
DB connection file (db.js):
var connection = mysql.createPool({
connectionLimit: 100,
host : 'xxxx',
port : xxxx,
user : 'username',
password : 'password',
database : 'myDB'
});
connection.getConnection(function(err) {
if (err) {
console.log('Error connecting: ' + err.stack)
return;
}
console.log('Connected as id ' + connection.threadId)
});
module.exports = connection;
Server.js
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
app = express();
var appRoutes = require('./routes/appRoutes');
app.use(express.static(path.join(__dirname, './client/build')));
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/api', appRoutes);
module.exports = app;
index.js
var app = require('./server');
//const { connection } = require('./database');
var port = 5001;
app.set('port', port);
app.listen(app.get('port'), () => {
console.log(`server on port ${app.get('port')}`);
});
AppModel.js
var sql = require('./db.js');
//Task object constructor
var Task = function(task){
this.task = task.task;
this.status = task.status;
this.created_at = new Date();
};
Task.getAllCustomerStatusRecords = function getAllCustomerStatusRecords(result) {
sql.query("Select a, b, c, call_provider_id from myTable order by id desc limit 20", function (err, res) {
if(err) {
console.log("error: ", err);
result(null, err);
}
else {
console.log('Customer status records : ', res);
result(null, res);
}
});
sql.releaseConnection()
};
I have a similar set up for another Node app but without mysql and it runs without issues.I'm not sure why it crashes in this case.
EDIT:
The API request does make a DB call. However that is only when the user explicitly selects some options and then makes a fetch call on the webpage. Initially though, there are no outwards API calls either to Db or external services.

How to solve "Router.use() requires a middleware function but got a Object at Function.use" error

I am getting an error when calling my router from my routes directory.I have made some changes in my code around some of the other posts on this issue but I can't get anything to solve.However i am not sure what exactly is wrong with my code below.
This is my error
[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
E:\Program Files\mean apps\shoppinglist\crud-backend\node_modules\express\lib\router\index.js:458
throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
^
TypeError: Router.use() requires a middleware function but got a Object
at Function.use (E:\Program Files\mean apps\shoppinglist\crud-backend\node_modules\express\lib\router\index.js:458:13)
at Function.<anonymous> (E:\Program Files\mean apps\shoppinglist\crud-backend\node_modules\express\lib\application.js:220:21)
at Array.forEach (<anonymous>)
at Function.use (E:\Program Files\mean apps\shoppinglist\crud-backend\node_modules\express\lib\application.js:217:7)
at Object.<anonymous> (E:\Program Files\mean apps\shoppinglist\crud-backend\app.js:42: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:279:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:752:3)
[nodemon] app crashed - waiting for file changes before starting...
I have this code in my app.js
//importing modules
var express = require('express');
var mongoose = require('mongoose');
var bodyparser = require('body-parser');
var cors = require('cors');
var path = require('path');
var app = express();
const route = require('./routes/route');
//conect to the mongodb
mongoose.connect('mongodb://localhost:27017/shoppinglist');
//on connection
mongoose.connection.on('connected',()=>{
console.log('Connected to database mongodb # 27017');
});
//error
mongoose.connection.on('error',(err)=>{
if(err)
{
console.log('Error in database connection:'+ err);
}
});
//port no
const port = 3000;
//adding middleware - cors
app.use(cors());
//body - parser
app.use(bodyparser.json());
//static files
app.use(express.static(path.join(__dirname, 'public')));
//routes
app.use('/api', route);
//testing server
app.get('/',(req, res)=>{
res.send('foobar');
});
app.listen(port,()=>{
console.log('Server started at port:' + port);
});
I have this code in my route.js
const express = require('express');
const router = express.Router();
const Item = require('../model/shoppingItem');
//retriving data from db
router.get('/items', (req, res, next)=>{
Item.find(function(err, items){
if(err){
res.json(err);
}
else{
res.json(items);
}
});
});
//insert data
router.post('item', (req, res, next)=>{
let newShoppingItem = new Item({
itemName: req.body.itemName,
itemQuantity: req.body.itemQuantity,
itemBought: req.body.itemBought
});
newShoppingItem.save((err, item)=>{
if(err){
res.json(err);
}
else{
res.json({msg: 'Item has been added successfully'});
}
});
});
You are using a module that you never exported.
app.use('/api', route);
but route was never exported - that's your main issue.
in your route module you can wrap everything in export default - alternatively you can use module.exports = router
This is an open source project I was working on try following the structure, if you still have issues let me know.
https://github.com/Muhand/nodejs-server

Route.post() requires a callback function but got a [object String]

I'm trying to make my vocabulary app using and changing MDN node/express tutorial.
MDN tutorial works perfectly but mines doesn't work.
Here are the errors :
Error: Route.post() requires a callback function but got a [object String]
at Route.(anonymous function) [as post] (d:\web-projects\vocastudy\node_modules\express\lib\router\route.js:202:15)
at Function.proto.(anonymous function) [as post] (d:\web-projects\vocastudy\node_modules\express\lib\router\index.js:510:19)
at Object.<anonymous> (d:\web-projects\vocastudy\routes\catalog.js:9:8)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Module.require (module.js:596:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (d:\web-projects\vocastudy\app.js:9:21)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
And app.js :
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var catalogRouter = require('./routes/catalog');
var app = express();
// Set up mongoose connection
var mongoose = require('mongoose');
var mongoDB = 'mongodb://127.0.0.1/vocastudy';
mongoose.connect(mongoDB);
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error'));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/catalog', catalogRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
And my routes catalog.js :
var express = require('express');
var router = express.Router();
var vocabulary_controller = require('../controllers/vocabularyController');
// GET request for creating a Word. NOTE This must come before routes tha display Word (uses id).
router.get('/create', vocabulary_controller.create_get);
/* POST create page */
router.post('/create', vocabulary_controller.create_post);
/* GET home page. */
router.get('/', vocabulary_controller.list);
/* GET detail page */
router.get('/:id', vocabulary_controller.detail);
module.exports = router;
And controllers vocabulary.js :
exports.create_post = [
// Validate fields
body('word').isLength({ min: 1 }).trim().withMessage('word must be specified'),
body('meaning').isLength({ min: 1 }).trim().withMessage('meaning must be specified'),
body('reference').isLength({ min: 1 }).trim().withMessage('reference must be specified'),
// Sanitize (trim and escape) the fields
sanitizeBody('word').trim().escape(),
sanitizeBody('meaning').trim().escape(),
sanitizeBody('reference').trim(),escape(),
// Process request after validation and sanitization
(req, res, next) => {
// Extract the validation errors from a request.
const errors = validationResult(req);
// Create vocabulary object with escaped and trimmed data.
if(!errors.isEmpty()) {
// There are errors.
res.render('create', { title: 'Create Word', word: req.body, errors: errors.array() });
return;
} else {
// Data from form is valid.
// Create a Vocabulary object with escaped and trimmed data.
var vocabulary = new Vocabulary({
word: req.body.word,
meaning: req.body.meaning,
reference: req.body.reference
});
vocabulary.save(function(err) {
if(err) { return next(err); };
// Successful - redirect to new word record.
res.redirect(vocabulary.url);
});
};
}
];
I think that create post controller is array so I got error but it perfectly works on MDN's tutorial version. I can't find my problem.
why did i get route.post error?
NB that mdn's tutorial is using array too.
It seems that in Express, app.post() accepts parameters that can be arrays of callbacks, but router.post() only accepts functions as callbacks. Try providing the array directly to an express app instead of the router, or as #TimothyLee suggested, use the spread syntax to turn the array into individual parameters to the router.post() function.

socket io .use() is not a function

Im trying to use sessions middleware to connect express and socket.io
However i get this error:
io.use(function(socket, next){
^
TypeError: io.use is not a function
at Object.<anonymous> (/home/ubuntu/workspace/newserver.js:30:4)
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
Here is my code:
var http = require('http');
var path = require('path');
var async = require('async');
var express = require('express');
var socketio = require('socket.io');
var sessions = require('express-session');
var mysql = require('mysql');
var RedisStore = require('connect-redis')(sessions);
var bodyParser = require('body-parser');
// App declaration
var router = express();
var server = http.createServer(router);
var io = socketio.listen(server);
io.set('log level',0);
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({extended:true}));
var sessionMiddleware = sessions({
store: new RedisStore({}),
secret: '901uj0394-0i4-#',
resave:true,
saveUninitialized:true
});
router.use(sessionMiddleware);
var session;
var appConfig = {
title: 'The Warring States 2'
};
router.set('views', path.resolve(__dirname,'client/views'));
router.set('view engine', 'pug');
var connection = mysql.createConnection({
// SQL Information
host: 'localhost',
user: 'boyton',
password: '',
database: 'WarringStates'
});
connection.connect(function(error){
// callback
if(!!error) {
console.log('Error!');
console.log(error);
}
else {
console.log('Connected to the database');
}
});
// Socket
var sockets = [];
var gamelobbies = [];
Im only starting out with node and expresss, I created a c9 container for node and installed the default Packages to work with the stack, Ive "tried" to update node and npm and express as well. However im not sure if they're up to the latest versions
here is what i get when i invoke check-node-versions
node: 4.7.3
npm: 2.15.11
yarn: not installed
express version 3.6.2
any help and input would be great. Thanks guys.
Change this line:
var io = socketio.listen(server);
to this:
// create an instance of socket.io, bound to our web werver
var io = socketio(server);
And, then make sure you have this somewhere:
// start the web server
server.listen(80);
The socketio library is a constructor and it wants you to call it and pass it the server to create the io object (an instance of the socket.io server). You then separately start the server so it can be used for both your http requests and your socket.io requests.
The way you were doing it, socketio was not the right kind of object to call .listen() on. It was the module handle rather than an instance and thus io was the wrong kind of object and thus why there was no .use() method.

Strange errors trying to use haml-coffee with an expressJS app

Here is my app.js file following the haml-coffee guides:
// misc requirements
var express = require('express')
, routes = require('./routes')
, http = require('http')
, path = require('path');
// setup app
var app = express();
// set default engine to haml-coffee
app.engine( 'hamlc', require('haml-coffee'.__express ));
// configure misc stuff
app.configure(function(){
app.set('port', process.env.PORT || 3000); // set localhost port to 3000
app.set('views', __dirname + '/views'); // setup views (templates)
app.set('view engine', 'hamlc'); // use haml-coffee as default templating engine
app.set('title', 'Learn Some Code'); // set the website title
app.use(express.favicon()); // favicon handling
app.use(express.logger('dev')); // logging
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router); // use the router
app.use(express.static(path.join(__dirname, 'public')));
});
// only configure this for development
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
But when I run node app.js... I get this strange error:
module.js:236
var start = request.substring(0, 2);
^
TypeError: Cannot call method 'substring' of undefined
at Function.Module._resolveLookupPaths (module.js:236:23)
at Function.Module._resolveFilename (module.js:328:31)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:362:17)
at require (module.js:378:17)
at Object.<anonymous> (/Users/chris/src/learnsomecode/app.js:11:22)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
Your require has a slight typo in it. Change
app.engine( 'hamlc', require('haml-coffee'.__express ));
to
app.engine( 'hamlc', require('haml-coffee').__express );
'haml-coffee'.__express resolves to undefined, which makes require(undefined) throw the Cannot call method 'substring' of undefined error.

Categories

Resources