Multiple var is node app.js - javascript

Is it bad form to have multiple var calls, such as:
var init = require('./config/init')(),
config = require('./config/config'),
express = require('express'),
errorHandler = require('errorhandler'),
bodyParser = require('body-parser'),
expressValidator = require('express-validator'),
mongoose = require('mongoose'),
path = require('path'),
_ = require('lodash'),
passport = require('passport'),
passport_config = require('./config/passport'),
session = require('express-session'),
MongoStore = require('connect-mongo')(session),
swagger = require("swagger-node-express"),
secrets = require('./config/secrets'),
multer = require('multer');
Or should I set each one by itself?

Since you're using it to import npm modules on a global scope, it's fine. But in general, it's better practice to declare var for each variable. The reason being that missing a , will create any following variables in a global scope. For example, try catching the error in this:
var init = require('./config/init')(),
config = require('./config/config'),
express = require('express'),
errorHandler = require('errorhandler'),
bodyParser = require('body-parser')
expressValidator = require('express-validator'),
mongoose = require('mongoose'),
path = require('path'),
_ = require('lodash'),
passport = require('passport'),
passport_config = require('./config/passport'),
session = require('express-session'),
MongoStore = require('connect-mongo')(session),
swagger = require("swagger-node-express"),
secrets = require('./config/secrets'),
multer = require('multer');

Related

Cant start my server when moving everything to 1 file

at the moment I have an app.js file and a server.js file. The server runs fine when I run 'node app.js' in CMD but I'm trying to put everything in the server.js file.
App.js:
var Server = require('./server.js').Server;
var server = new Server();
server.initialise(8080);
Server.js:
var express = require('express');
var http = require('http');
var events = require('events');
var io = require('socket.io');
var app = express();
exports.Server = Server = function() {
this.userId = 1;
};
Server.prototype.initialise = function(port) {
this.server = http.createServer(app);
app.use(express.static('public'));
this.server.listen(port);
this.startSockets();
this.em = new events();
console.log('Server running on port: ' + port);
};
So I've tried moving the last 2 lines of app.js to the server but I'm getting the error that Server isnt a constructer. I've tried
var Server = this;
I've also tried
this.initialise(8080);
Nothing seems to work

nodeJS: Sending html data from one js to another

The code below is working
var express = require('express')
var app = express();
var fs = require('fs')
var addUserToDB = require('./addUserToDB')
app.use('addUserToDB', addUserToDB)
app.get('/register.html', function(req,res){
res.sendFile(__dirname+ "/" + "register.html");
})
var server = app.listen(8087,function(){
console.log("Listening at 8087");
})
app.get('/addUserToDB',function(req,res){
firstname = req.query.firstname;
console.log(firstname)
})
app.get('/register.html', function(req,res){
res.sendFile(__dirname+ "/" + "register.html");
})
However, when I try to remove the following method and place it into another .js file so I can get the firstName from that file. It's not working. The following code is in addUserToDB.js:
var addUserToDB = app.get('/addUserToDB',function(req,res){
firstname = req.query.firstname;
console.log(firstname)
})
module.exports = addUserToDB;
I have tried making a addUserToDB.js file and added the code
var express = require('express')
var app = express();
app.get('addUserToDB',function(req,res){
firstname = req.query.firstname;
console.log(firstname)
})
but it seems I am missing something because it doesn't work. Thanks.
A few things here. First, need to do a require of addUserToDB.js from server.js (I will assume that's the name of your main file) and then use it as a middleware. Also, you need to export the app from addUserToDB.js.
server.js:
var express = require('express')
var app = express();
var fs = require('fs')
var addUserToDB = require('./addUserToDB');
app.get('/register.html', function(req,res){
res.sendFile(__dirname+ "/" + "register.html");
})
var server = app.listen(8087,function(){
console.log("Listening at 8087");
})
app.use(addUserToDB);
addUserToDB.js:
var express = require('express')
var router = express.Router();
router.get('/addUserToDB',function(req,res){
firstname = req.query.firstname;
console.log(firstname)
})
module.exports = router;

express js route is not working, getting a 404 for some reason

I have a link that is suppose to go to a page but every time I click on the link the address changes to the right page but I get a 404 Not Found error.
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 fs = require("fs");
var routes = require('./routes/index');
var login = require('./routes/login');
var rtc = require('./routes/rtc');
var adminEstimating = require('./routes/adminEstimating');
var adminEWJ = require('./routes/adminEWJ');
var adminTrusses = require('./routes/adminTrusses');
var admin = require('./routes/admin');
var adminMillwork = require('./routes/adminMillwork');
var adminInsulation = require('./routes/adminInsulation');
var adminDrywall = require('./routes/adminDrywall');
var submitted = require('./routes/submitted');
var adminLink = require('./routes/adminLink');
var notAdmin = require('./routes/notAdmin');
var error = require('./routes/error');
var dogReport = require('./routes/dogReport');
var fleetReport = require('./routes/fleetReport');
var fleetLogin = require('./routes/fleetLogin');
var fleetNotAdmin = require('./routes/fleetNotAdmin');
var fleetAdminLink = require('./routes/fleetAdminLink');
var fleetAdminNew = require('./routes/fleetAdminNew');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
var env = process.env.NODE_ENV || 'development';
app.locals.ENV = env;
app.locals.ENV_DEVELOPMENT = env == 'development';
// app.use(favicon(__dirname + '/public/img/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/leadtime/', routes);
app.use('/leadtime/', function(req, res, next){
var fileName = './public/components/visitorTracker.json';
var fileContent = fs.readFileSync(fileName);
var content = JSON.parse(fileContent);
content.visitorCount++;
fs.writeFileSync(fileName, JSON.stringify(content));
next();
});
app.use('/leadtime/login', login);
app.use('/leadtime/rtcProduction', rtc);
app.use('/leadtime/adminEstimating', adminEstimating);
app.use('/leadtime/adminEWJ', adminEWJ);
app.use('/leadtime/adminTrusses', adminTrusses);
app.use('/leadtime/admin', admin);
app.use('/leadtime/adminMillwork', adminMillwork);
app.use('/leadtime/adminInsulation', adminInsulation);
app.use('/leadtime/adminDrywall', adminDrywall);
app.use('/leadtime/submitted', submitted);
app.use('/leadtime/adminLink', adminLink);
app.use('/leadtime/notAdmin', notAdmin);
app.use('/leadtime/error', error);
app.use('/dogReport', dogReport);
app.use('/fleetReport', fleetReport);
app.use('/fleetReport/fleetLogin', fleetLogin);
app.use('/fleetReport/fleetNotAdmin', fleetNotAdmin);
app.use('/fleetReport/fleetAdminLink', fleetAdminLink);
app.use('/fleetReport/fleetAdminNew', fleetAdminNew);
The route that isn't working is var fleetAdminNew = require('./routes/fleetAdminNew');
I've done the same thing for all my other routes and have had no problems. I've looked for spelling mistakes and I haven't found any.
fleetAdminNew.jade
extends layout
block content
div(class='container')
header
h1 National Lumber Co. / Reliable Truss & Component
h2 Fleet Maintenance Administration
div(class='section')
h3 New Truck
form(method='POST')
label(for='yard') Yard
input(type='text' id='yard')
label(for='vehicle#') Vehicle #
input(type='text' id='vehicle#')
label(for='vehicleDescription') Vehicle Description
input(type='text' id='vehicleDescription')
fleetAdminNew.js (not finished yet, still need to put post code in)
var express = require('express');
var fs = require("fs");
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('fleetAdminNew', { title: 'Add New Truck' });
});
module.exports = router;
If you have a folder 'routes/fleetAdminNew' then it's pulling the nothing from that instead.

Mongoose MissingSchemaError happening inconsistently with Mocha test

In users.spec.js I have this and it works fine:
var mongoose = require('mongoose');
var assert = require('assert');
var request = require('supertest');
var app = require('../../app.js');
var User = mongoose.model('User');
var Local = mongoose.model('Local');
var agent = request.agent(app);
var invalidId = 'aaaaaaaaaaaaaaaaaaaaaaaa';
In app.js I have:
mongoose.connect(dbUrl);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'Problem connecting to database.'));
db.once('open', function onDbConnect() {
console.log('Connected to ' + dbUrl + ' database...');
// create models
require('./api/users/user.model.js');
And in user.model.js I have:
var User = mongoose.model('User', userSchema);
var Local = mongoose.model('Local', localSchema);
So when users.spec.js is run, it first creates the models, and then I can reference them by mongoose.model('User') and mongoose.model('Local').
However, in auth.spec.js, I'm doing the same thing, and it's not working:
var mongoose = require('mongoose');
var assert = require('assert');
var request = require('supertest');
var app = require('../../app.js');
var User = mongoose.model('User');
var Local = mongoose.model('Local');
var agent = request.agent(app);
Output:
/Users/azerner/code/mean-starter/node_modules/mongoose/lib/index.js:332
throw new mongoose.Error.MissingSchemaError(name);
^
MissingSchemaError: Schema hasn't been registered for model "User".
Use mongoose.model(name, schema)
at Mongoose.model (/Users/azerner/code/mean-starter/node_modules/mongoose/lib/index.js:332:13)
at Object.<anonymous> (/Users/azerner/code/mean-starter/server/api/auth/auth.spec.js:5:21)
Why is this? I'm running the tests separately: mocha server/api/auth and mocha server/api/users, so they shouldn't be interfering with one another.
Full code here.
Note: this works, but I'd prefer not to use it. Or at least I'd like to understand what the problem is and why this works.
// :( https://github.com/Automattic/mongoose/issues/1251
// it isn't exactly my issue, but the recommendation on the bottom works
try {
var User = mongoose.model('User');
var Local = mongoose.model('Local');
}
catch(e) {
var schemas = require('../users/user.model.js');
var User = mongoose.model('User', schemas.UserSchema);
var Local = mongoose.model('Local', schemas.LocalSchema);
}

scoket.io is not found when listening to different port than server

I have set up a server in node.js using socket.io and epxress.
When I set it up as shown below, it works like charm (now it's listening on 8080).
var express = require("express");
var http = require("http");
var io = require("socket.io");
var app = express();
var server = http.createServer(app).listen(port, host);
var scoketIO = io.listen(server);
But I need it to listen to different port, and if I try eg. 8000
var app = express();
var server = http.createServer(app).listen(port, host);
var scoketIO = io.listen(8000);
I get the following error:
GET http://10.0.33.34:8080/socket.io/socket.io.js 404 (Not Found). Can anybody please help me?
var express = require("express");
var http = require("http");
var io = require("socket.io");
var app = express();
var port = 8000;
var server = http.createServer(app).listen(port, host);
var scoketIO = io.listen(server);
Above code is not tested but most likely it will not fail. Pass port value to listen method of http.createServer(app).
var express = require('express')
http = require('http');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(8000);
//Code needs to be in this order
and check in the script that the port is 8000
<script src=""></script>
Do you include the script in you html ?
Maybe change the include to the port 8000.
<script src="http://10.0.33.34:8000/socket.io/"></script>

Categories