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

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.

Related

Type error: cannot find module body-parser

I tried making a project on my own and this error happened. I couldn't fix it. It just somehow happens and I am so confused where to start looking for the error.
app.js
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.set('view engine', 'ejs');
app.set('views', 'views');
const adminData = require('./routes/admin');
const shopRoutes = require('./routes/shop');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/admin', adminData.routes);
app.use(shopRoutes);
app.use((req, res, next) => {
res.status(404).render('404', { pageTitle: 'Page Not Found' });
});
app.listen(3000);
admin.js
const path = require('path');
const express = require('express');
const rootDir = require('../util/path');
const router = express.Router();
const products = [];
// /admin/add-product => GET
router.get('/add-product', (req, res, next) => {
res.render('add-product', {
pageTitle: 'Add Product',
path: '/admin/add-product',
formsCSS: true,
productCSS: true,
activeAddProduct: true
});
});
// /admin/add-product => POST
router.post('/add-product', (req, res, next) => {
products.push({ title: req.body.title });
res.redirect('/');
});
exports.routes = router;
exports.products = products;
shop.js
code snippet of shop.js
This is my error.
I am making a webpage for the first time using this.
internal/modules/cjs/loader.js:638
throw err;
^
Error: Cannot find module 'body-parser'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
at Function.Module._load (internal/modules/cjs/loader.js:562:25)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Object.<anonymous> (C:\Users\User\Documents\My Website\05-working-on-layout-with-partials\app.js:4:20)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
[nodemon] app crashed - waiting for file changes before starting...
Please try to install the required body-parser module,
Use following command to do so.
npm install body-parser
Please install the dependency i.e body-parser
npm i body-parser --save
Error is on the 4th line of app.js its not getting the body-parser module

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.

how to use connect-orientdb module with express

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.

Handlebars Templating Engine Not Defined

I am working through Web Development with Node & Express: Leveraging the JavaScript Stack, by Ethan Brown. I am working in chapter three, which introduces basic concepts concerning Express. I created the app, meadowlark.js, as the book has said, and I am getting this error concerning the Handlebars Templating Engine:
ReferenceError: handlebars is not defined
at Object.<anonymous> (/PROJECT_STORAGE/site/meadowlark.js:7:26)
at Module._compile (module.js:410:26)
at Object.Module._extensions..js (module.js:417:10)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Function.Module.runMain (module.js:442:10)
at startup (node.js:136:18)
at node.js:966:3
Here is the code for how I setup Handlebars and the rest of meadowlark.js:
var express = require('express');
var app = express();
// setup handlebars view engine
var handlbars = require('express-handlebars').create({ defaultLayout: 'main' });
app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');
app.set('views', __dirname + '/views');
app.set('port', process.env.PORT || 3000);
app.get('/', function(req, res) {
res.render('home');
});
app.get('/about', function(req, res) {
res.type('about');
});
// custom 404 pg
app.use(function(req, res) {
res.status(404);
res.render('404');
});
// custom 500 pg
app.use(function(err, req, res, next) {
//console.error(err.stack);
res.status(500);
res.render('500');
});
app.listen(app.get('port'), function() {
console.log('Express started on localhost:' + app.get('port') + '; press Ctrl-C to terminate.');
});
How can I fix my code to make Handlebars initialize correctly and make handlebars.js run?
Typo var handlbars = require('express-handlebars').create({ defaultLayout: 'main' });
should be var handlebars.
Pro tip: Use a linter in your ide.

Object #<Server> has no method 'use' [Express+ShareJS]

Environment
Express 3.2.4
ShareJS 0.6.2
OS X 10.8.3
Goal
I am trying to get ShareJS running inside of an Express app.
Problem
I get the following error on running node app.js:
/Users/eric/Documents/Projects/collabit/node_modules/share/src/server/index.coffee:52
server.use(options.staticpath, connect["static"]("" + __dirname + "/../.
^
TypeError: Object #<Server> has no method 'use'
at Function.create.attach.attach (/Users/eric/Documents/Projects/collabit/node_modules/share/src/server/index.coffee:52:14)
at Object.<anonymous> (/Users/eric/Documents/Projects/collabit/app.js:43:16)
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)
at Module.runMain (module.js:492:10)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)
I used the express cli interface to generate an app and was working with SocketIO just fine before deciding to swap in ShareJS. I'm pretty sure my issue is how I'm crafting the server but I don't know enough to figure out how I should be creating the server object to keep the express functionality but allow ShareJS to attach.b
Code
/**
* Module dependencies.
*/
var express = require('express')
, sharejs = require('share')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/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')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
app.get('/users', user.list);
var server = http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
/**
* ShareJS Code
*/
var options = {db: {type: 'none'}};
sharejs.server.attach(server, options);
Question
What is the proper way to create my server object in order to allow ShareJS to attach to it while retaining the Express functionality.
Thanks!
Thanks in advance for help and let me know if any additional information is needed.
I had a similar issue. After a lot of trial and error this worked for me:
var express = require('express'),
http = require('http'),
sharejs = require('share').server;
var app = express();
var server = http.createServer(app);
var options = {db:{type:'none'}}; // See docs for options. {type: 'redis'} to enable persistance.
// Attach the sharejs REST and Socket.io interfaces to the server
sharejs.attach(app, options);
app.use(app.router);
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
server.listen(8000, function () {
console.log('Server running at http://127.0.0.1:8000/');
});
app.get('/', function(req, res) {
res.render('share.html');
});
Then in views/share.html I had the standard example html:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="http://ajaxorg.github.com/ace/build/src/ace.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="/channel/bcsocket.js"></script>
<script src="/share/share.js"></script>
<script src="/share/ace.js"></script>
<script>
$(document).ready(function() {
var editor = ace.edit("editor");
sharejs.open('hello', 'text', 'http://localhost:8000/channel', function (error, doc) {
doc.attach_ace(editor);
});
});
</script>
<style>
#editor {
width: 200px;
height: 100px;
}
</style>
</head>
<body>
<div id="editor"></div>
</body>
</html>

Categories

Resources