I'm following the docs on the github of Share.js but can't seem to get it to work
https://github.com/share/ShareJS/wiki/Getting-started-%280.6.x%29
I built a base app with the Express generator. It put the main server file inside /bin/www which is not supposed to be modified (I tried it).
The problem is with the code below.
var connect = require('connect'),
sharejs = require('share').server;
var server = connect(
connect.logger(),
connect.static(__dirname + '/public')
);
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(server, options);
server.listen(8000, function(){
console.log('Server running at http://127.0.0.1:8000/');
});
It requires me to set up server.listen(...) in the app.js but it's already been done in the /bin/www file.
My app.js looks like the code below.
var express = require('express');
var engine = require('ejs-locals');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('ejs', engine);
app.set('view engine', 'ejs');
// database setup
var dbConfig = require('./db.js');
var mongoose = require('mongoose');
// connect to DB
mongoose.connect(dbConfig.url, function (err) {
if (err) {
console.log(err);
}
});
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Configuring Passport
var passport = require('passport');
var expressSession = require('express-session');
app.use(expressSession({
secret: 'mySecretKey',
resave: true,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
// Using the flash middleware provided by connect-flash to store messages in session
// and displaying in templates
var flash = require('connect-flash');
app.use(flash());
// Initialize passport
var initPassport = require('./passport/init');
initPassport(passport);
// Configuring Routes
var routes = require('./routes/index')(passport);
var users = require('./routes/users');
var editor = require('./routes/editor')(passport);
app.use('/', routes);
app.use('/editor', editor);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
if (req.session.user) {
app.locals.user = req.session.user
}
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
Related
Im having trouble connecting Node.js application with sql database.
Error occurs is "req.getConnection is not a function".
I am trying to get data from the database the moment I click on a certain page (eg.users).
My code is as below
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var flash = require('express-flash');
var session = require('express-session');
var expressValidator = require('express-validator');
var methodOverride = require('method-override');
var connection = require('express-myconnection');
var mysql = require('mysql');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(session({secret:"mysecretpass"}));
app.use(flash());
app.use(expressValidator());
app.use(cookieParser());
app.use(require('less-middleware')(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use(methodOverride(function(req, res){
if (req.body && typeof req.body === 'object' && '_method' in req.body)
{
var method = req.body._method;
delete req.body._method;
return method;
}
}));
/*-----------------------------------------
* Connection peer, register as middleware
* type koneksi:single,pool and request
-----------------------------------------*/
app.use(
connection(mysql,{
host:'localhost',
user:'root',
password:'',
port:3306,
database:'stores'
},'single')
);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
routes/index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('dashboard', { title: 'Dashboard' });
});
router.get('/admin_users', function(req, res, next) {
req.getConnection(function(err,connection){
var query = connection.query('SELECT * FROM users',function(err,rows)
{
if(err)
var errornya = ("Error Selecting : %s ",err );
req.flash('msg_error', errornya);
res.render('admin_users',{title:"Admin Users",data:rows});
});
//console.log(query.sql);
});
});
module.exports = router;
You are adding the express-myconnection middleware after your routes middleware. Middleware is executed in the order it is added, and as such the getConnection function is not defined on the req object until after your express-myconnection middleware is executed.
Simply move the connection middleware above the usage of routes, ie.
app.use(
connection(mysql,{
host:'localhost',
user:'root',
password:'',
port:3306,
database:'stores'
},'single')
);
app.use('/', routes);
app.use('/users', users);
I have a Experss.js framework and Node.js with a request to MS SQL database on the server side.
I want to get a data(in JSON or array) from server and send to Cliend side.
I don't understand how can I write routers for another server on the Client side.
server.js
npm start
http://localhost:5000/
Code:
var sql = require("mssql");
var express = require('express');
var app = express();
var http = require('http')
var query = "SELECT AVG([sta_waittime]) AS Spalte FROM [DialogMaster_TEST].[dwh].[anruf_stat] WHERE CONVERT(DATE,sta_timestamp) = CONVERT(DATE,CONVERT(DATE,'2016-08-01')) ";
app.get('/', function (req, res) {
sql.connect("mssql://log:pas#db/TEST").then(function() {
// Query
new sql.Request().query(query).then(function(recordset) {
var a = [];
a.push(recordset[0].Spalte);
res.send(a); // **number**
}).catch(function(err) {
// ... query error checks
});
}).catch(function(err) {
// ... connect error checks
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
Server site in Browser:
My app.js file.
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
//app.get('/');
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
You need only 1 server(REST server). Just use node.js server.
Read it:
REST
I'm following this tutorial: http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/
When I do db.usercollection.find().pretty() in my mongo terminal, my records print - so I know I have records to display.
When I do http://localhost:3000/userlist in my browser, I get the words "User List" at the top - but I don't get any of the user data.
It should look like this.
Question: Is my link in my userlist.jade file not pointing to the database data??
userlist.jade
extends layout
block content
h1.
User List
ul
each user, i in userlist
li
a(href="mailto:#{user.email}")= user.username
index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
/* GET Userlist page. */
router.get('/userlist', function(req, res) {
var db = req.db;
var collection = db.get('usercollection');
collection.find({},{},function(e,docs){
res.render('userlist', {
"userlist" : docs
});
});
});
module.exports = router;
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// new code
// we want to talk to mongodb, use monk to do it, databasebase is lcoated at localhost:27017/nodetest1
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/nodetest1');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Make our db accessible to our router - new code
app.use(function(req,res,next){
req.db = db;
next();
});
// telling Express what route files to use
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
// our master app exporting its app object. All modules export an object whch can easily be called elsewhere in code.
module.exports = app;
i was getting the same error and then i fixed the problem:
app.js
var db = monk('localhost:27017/nodetest1');
change the localhost to 127.0.0.1
and make sure the collection name is nodetest1
I'm starting to learn Node and Express, but I currently can't get some of my routes to work.. Here's the app.js file that I'm currently using
EDIT: Here's my updated files, but I stil get a 404
var db = require('./db');
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false,
}));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/users', users);
app.use('/', routes);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
//res.send(req.path)
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
And the route I can't view is '/users/userlist' here is my userlist.js route
EDIT: I've moved '/users/userlist' into the users.js route
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var User = mongoose.model('User');
/* GET users listing. */
router.get('/users/add/*:', function(req, res, next) {
var params = req.params[0].split("/");
if(params.length>=2){
var newUser = new User({username: params[0], password:params[1]});
newUser.save(function(err, fluffy){
if(err)
res.send(err);
});
}
res.send('Account Created!');
});
router.get('/users/userlist', function(req, res) {
var users;
User.find(function(err, _users){
if(err)
users="ERROR";
else
users=_users;
});
res.send(users);
});
module.exports = router;
When I try and point my browser to http://localhost:3000/users/userlist I just get a 404.
You have made a mistake while declaring routes in app.js,remove below code.
app.use('/users/userlist',userlist);
I am new to NodeJS and ExpressJS. I am following this tutorial http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/ for creating and connecting mongodb with nodejs. Everything works perfectly(DB data inserting through command line,package.json config) except db connection, it throws undefined error.
var monk = require('monk');
var db = monk('localhost:27017/deno');
I check this in console like this console.log(db) it shows 'undefined' in index.js
My app.js is :
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// New Code
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/Fujitsu');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Make our db accessible to our router
app.use(function(req,res,next){
req.db = db;
next();
});
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
routes/index.js is
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
/************ Customized starts Here **********/
/* GET Userlist page. */
router.get('/userlist', function(req, res) {
var db = req.db;
console.log(db);
var collection = db.get('usercollection');
collection.find({},{},function(e,docs){
res.render('userlist', {
"userlist" : docs
});
});
});
/******** Customized - Ends here ***********/
module.exports = router;
Please anyone of you tell me the solution because now I'm struggling with this.
Thanks In Advance.