Added socket.io to back-end, it broke everything - node.js

Well, as the title suggests, I broke everything using socket.io. Mainly because the way it calls express breaks everything else using express.
Here is my old way of doing it:
/*jshint esversion: 6*/
const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
const path = require('path');
const expressValidator = require('express-validator');
const flash = require('connect-flash');
const session = require('express-session');
const passport = require('passport');
const fs = require('fs');
const db = require('./config/db');
// Init App
app = express();
// View Engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Bodyparser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false,
}));
// Set Static path
app.use(express.static(path.join(__dirname, 'static')));
Which works wonders! It works, however adding socket.io like so:
/*jshint esversion: 6*/
const app = require('express')();
const http = require('http').Server(app);
const socket = require('socket.io')(http);
const bodyParser = require('body-parser');
const path = require('path');
const expressValidator = require('express-validator');
const flash = require('connect-flash');
const session = require('express-session');
const passport = require('passport');
const fs = require('fs');
const db = require('./config/db');
// Init App
// app = express();
// View Engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Bodyparser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false,
}));
// Set Static path
app.use(express.static(path.join(__dirname, 'static')));
Breaks everything using express.* because it is saying express is not defined. So my static path gets broken and of course the app crashes.I tried several solutions, but to no avail.
Oops forgot to add the error:
app.use(express.static(path.join(__dirname, 'static')));
^
ReferenceError: express is not defined

Try this. The idea is that you need to import express. Socket.io can be required once the rest is defined.
/*jshint esversion: 6*/
const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
const path = require('path');
const expressValidator = require('express-validator');
const flash = require('connect-flash');
const session = require('express-session');
const passport = require('passport');
const fs = require('fs');
const db = require('./config/db');
// Init App
const app = express();
// Init http server
const server = http.createServer(app);
// Init socket
const socket = require('socket.io').listen(server);
// View Engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Bodyparser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false,
}));
// Set Static path
app.use(express.static(path.join(__dirname, 'static')));

Related

express.static() doesn't exist

When using express.static() in the code below I get an error telling me that the function doesn't exist.
This is my code:
var app = require("express");
var consign = require("consign");
var bodyParser = require("body-parser")
var expressValidator = require("express-validator");
var express = app();
express.set('view engine', 'ejs');
express.set('views', './app/views');
express.use(express.static("./app/public"));
express.use(bodyParser.urlencoded({extended: true}));
express.use(expressValidator());
consign()
.include('app/routes')
.then('config/db.js')
.then('app/models')
.then('app/controllers')
.into(express);
module.exports = express;
var express = require("express"); // !!!
var consign = require("consign");
var bodyParser = require("body-parser")
var expressValidator = require("express-validator");
var app = express(); // !!!
app.set('view engine', 'ejs');
app.set('views', './app/views');
app.use(express.static("./app/public"));
app.use(bodyParser.urlencoded({extended: true}));
app.use(expressValidator());
consign()
.include('app/routes')
.then('config/db.js')
.then('app/models')
.then('app/controllers')
.into(app); // !!!
module.exports = express;
https://expressjs.com/en/starter/static-files.html
Eu falo inglês, desculpe. Eu normalmente daria uma explicação.
English: I speak English, sorry. I would usually give an explanation.

server.use(express.static(path.join(__dirname, 'public'))); not working

CSS and Images files are not working in my application getting error "Refused to apply style from '' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled"
I have tried "server.use(express.static(path.join(__dirname, 'public')));" but still not working ...
const express = require('express');
//const expressLayouts = require('express-ejs-layouts');
const mongoose = require('mongoose'); mongoose.set('useCreateIndex', true);
const passport = require('passport');
const flash = require('connect-flash');
const session = require('express-session');
const server = express();
const path = require("path");
const bodyParser = require("body-parser");
//Set path for static assets
//server.use(expressLayouts);
server.set('view engine', 'ejs');
//server.set('view options', { layout: false });
server.set('views', path.join(__dirname, 'views'));
server.engine('html', require('ejs').renderFile);
//Set path for static assets
server.use(express.static(path.join(__dirname, 'public')));
// Express body parser
server.use(express.urlencoded({ extended: true }));

middleware function error in expressjs

I unable to run node main file in terminal
and I am using handlebar as template engine
getting this weird error
I did npm install all dependencies which is required. but still getting this error.
/home/mohsin/Desktop/mohsin/react/react-web-app/node_modules/express/lib/application.js:210
throw new TypeError('app.use() requires a middleware function')
^
TypeError: app.use() requires a middleware function
this is error screenshot please have look https://i.imgur.com/c6zoaA6.png
My app.js file
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const exphbs = require('express-handlebars');
const expressValidator = require('express-validator');
const flash = require('connect-flash');
const session = require('express-sessions');
const passport = require('passport');
const mongoose = require('mongoose');
// Port env
const port = 3000;
// Route files
const index = require('./routes/index');
const user = require('./routes/user');
// Init App
const app = express();
// View Engine
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
// Static Folder
app.use(express.static(path.join(__dirname, 'public')));
// Body parser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
// Express Session
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
// Start server
app.use('/', index);
app.use('/user', user);
// Start Server
app.listen(port, () => {
console.log('Server started on port '+port);
});
There is no package named 'express-sessions'
instead use express-session
so its not returning any method. which app.use can call as method.
Here is package

Run Node.js Shell_Exec command onclick

I'm building a home automation system in NodeJS and I want to fire some commands on my raspberry pi using the Shell_exec function in Express. How can I do this with an onclick event in JADE?
This is my app.js in Express:
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 shell_exec = require('shell_exec').shell_exec;
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/homeapp');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var index = 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/images', 'favicon-32x32.png')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(passport.initialize());
app.use(passport.session());
var User = require('./models/User');
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
module.exports = app;
And this is my index.js with the routing:
var express = require('express');
var router = express.Router();
var auth = require('../controller/AuthController.js');
router.get('/', auth.home);
router.get('/login', auth.login);
router.post('/login', auth.doLogin);
router.get('/logout', auth.logout);
module.exports = router;
And this is the jade file where I want the onclick event to exucute the commands:
div.btn(onclick="shell_exec");
You can't call any Node.js command from Jade view. Jade view is parsed in client's browser and any javascript commands you write in that file will be executed in browser.
In the view you should add code which will create AJAX request to the node.js server and in the node.js app create route which will handle the request and execute the command (shell_exec).

How could router be "undefined" here in my Node app?

var express = require('express')
var router = express.Router();
I am debugging my Node app and express is defined, but after stepping over the var router line, router is still undefined, how could this happen?
Well here is all the code if you must:
var express = require('express')
// , fancy_scripts = require('./fancy_scripts')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, 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/sparks');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.engine('html', require('ejs').renderFile);
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.use(express.static(__dirname + '/fancy_scripts'));
app.use('/fancy_scripts', express.static(__dirname + '/fancy_scripts'));
app.use(function(req,res,next){
req.db = db;
next();
});
app.get('/', routes.index);
//var router = express.Router();
//
///* GET home page. */
//router.get('/', routes.index);
If were to guess the line app.use(app.router);
might be the culprit...?

Resources