I have an application on nodejs running on a kinghost.com host, it enabled SSL we will encrypt, but my application still does not respond with https only by http. I made this setting below in the application so that the requests were turned into https, but it did not work. Could someone tell me what to do, where I am wrong, some example. I do not know what else to do.
File app.js
app.set('port', process.env.PORT || 21019);
app.listen(app.get('port'));
app.use(function(req, res, next) {
if ((req.get('X-Forwarded-Proto') !== 'https')) {
res.redirect('https://' + req.get('Host') + req.url);
} else
next();
});
Full app.js file
var express = require('express');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var logger = require('morgan');
var path = require('path');
var fileUpload = require('express-fileupload');
var https = require('https');
var app = express();
var expressValidator = require('express-validator');
var passport = require('passport');
var flash = require('connect-flash');
// - Cria rotas
var routes = require('./routes/index');
var usuarios = require('./routes/usuario');
var motorista = require('./routes/motorista');
var login = require('./routes/login');
var aluno = require('./routes/aluno');
var contrato = require('./routes/contrato');
var boleto = require('./routes/boleto');
var pessoa = require('./routes/pessoa');
require('./security/autenticacao')(passport);
app.use(logger('dev'));
app.use(expressValidator());
app.use(cookieParser());
app.use(bodyParser.json({limit: "50mb"}));
app.use(bodyParser.urlencoded({limit: "50mb", extended: true, parameterLimit:50000}));
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(session({
secret: 'reis&turlwaysrunning',
resave: true,
saveUninitialized: true
} ));
app.use(logErrors);
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(function (req, res, next) {
res.locals.login = req.user;
next();
});
app.use(fileUpload());
app.set('port', process.env.PORT || 21019);
app.listen(app.get('port'));
app.use(function(req, res, next) {
if ((req.get('X-Forwarded-Proto') !== 'https')) {
res.redirect('https://' + req.get('Host') + req.url);
} else
next();
});
// Atriui rotas
app.use('/home', routes);
app.use('/usuarios', usuarios);
app.use('/alunos', aluno);
app.use('/motoristas', motorista);
app.use('/contratos', contrato);
app.use('/login', login);
app.use('/boletos', boleto);
app.use('/pessoas', pessoa);
//app.listen(port);
function logErrors (err, req, res, next) {
console.error('Troxa: ' + err.stack)
next(err)
}
module.exports = app;
I tried that too and it did not work
File app.js
https.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Hello World!');
res.end();
}).listen(21019);
Full app.js file
var express = require('express');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var logger = require('morgan');
var path = require('path');
var fileUpload = require('express-fileupload');
var https = require('https');
var app = express();
var expressValidator = require('express-validator');
var passport = require('passport');
var flash = require('connect-flash');
// - Cria rotas
var routes = require('./routes/index');
var usuarios = require('./routes/usuario');
var motorista = require('./routes/motorista');
var login = require('./routes/login');
var aluno = require('./routes/aluno');
var contrato = require('./routes/contrato');
var boleto = require('./routes/boleto');
var pessoa = require('./routes/pessoa');
require('./security/autenticacao')(passport);
app.use(logger('dev'));
app.use(expressValidator());
app.use(cookieParser());
app.use(bodyParser.json({limit: "50mb"}));
app.use(bodyParser.urlencoded({limit: "50mb", extended: true, parameterLimit:50000}));
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(session({
secret: 'reis&turlwaysrunning',
resave: true,
saveUninitialized: true
} ));
app.use(logErrors);
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(function (req, res, next) {
res.locals.login = req.user;
next();
});
app.use(fileUpload());
https.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Hello World!');
res.end();
}).listen(21019);
// Atriui rotas
app.use('/home', routes);
app.use('/usuarios', usuarios);
app.use('/alunos', aluno);
app.use('/motoristas', motorista);
app.use('/contratos', contrato);
app.use('/login', login);
app.use('/boletos', boleto);
app.use('/pessoas', pessoa);
//app.listen(port);
function logErrors (err, req, res, next) {
console.error('Troxa: ' + err.stack)
next(err)
}
You need to have your https credential (i.e cert and key ) to use https. You can use this to generate the credentials
openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out cert.pem
var fs = require('fs');
var https = require('https');
var httpsServerOptions = {
'key': fs.readFileSync('./https/key.pem'),
'cert': fs.readFileSync('./https/cert.pem')
};
var express = require('express');
var app = express();
// your express configuration here
var httpsServer = https.createServer(httpsServerOptions, app);
httpsServer.listen(21019);
You could try the method of implementing https with express as shown here Enabling HTTPS on express.js ?
If free Let's Encrypt certificates are good enough for you, you could use Greenlock and get free SSL with automated renewal.
Greenlock: Free SSL, Automated HTTPS
Greenlock handles certificate issuance and renewal (via Let's Encrypt) and http => https redirection, out-of-the box.
Instead of calling .listen() from express, you just export your express app (or any node-http compatible function).
Simplified, that looks like this:
express-app.js:
var express = require('express');
var app = express();
app.use('/', function (req, res) {
res.send({ msg: "Hello, Encrypted World!" })
});
// DO NOT DO app.listen()
// Instead export your app:
module.exports = app;
Then you can use node's http and https for your server, or you can use greenlock express, which sets it up for you:
server.js:
require('greenlock-express').create({
// Let's Encrypt v2 is ACME draft 11
version: 'draft-11'
, server: 'https://acme-v02.api.letsencrypt.org/directory'
// You MUST change these to valid email and domains
, email: 'john.doe#example.com'
, approveDomains: [ 'example.com', 'www.example.com' ]
, agreeTos: true
// This should be the directory to which certificates are saved
, configDir: "/path/to/project/acme/"
, app: require('./express-app.js')
, communityMember: true // Get notified of important updates
, telemetry: true // Contribute telemetry data to the project
}).listen(80, 443);
Screencast
Watch the QuickStart demonstration: https://youtu.be/e8vaR4CEZ5s
More Info
See https://stackoverflow.com/a/51146209/151312
Related
Using csurf, I am trying to integrate csrf protection into my node.js express 4 application. This is my code:
EDIT: The code below was updated according to the solution I found.
"use strict";
var http = require('http');
var https = require('https');
var port = process.env.PORT || 80,
express = require('express'),
csrf = require('csurf'),
bodyParser = require('body-parser');
var LocalStrategy = require('passport-local').Strategy,
csrfProtection = csrf({ cookie: true }),
mongoose = require('mongoose'),
conn = mongoose.createConnection('foo'),
cookieParser = require('cookie-parser'),
passport = require('passport'),
session = require('express-session'),
MongoStore = require('connect-mongo')(session),
app = express();
app.set('view engine', 'ejs');
var csrfProtection = csrf({ cookie: true }); // doesn't work either
require('passport')(passport);
app.use(cookieParser("foo"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true})); //extended: true|false does not make any difference
app.use(session({
//foo
}));
app.use(passport.initialize());
app.use(passport.session());
require('./app/routes.js')(app, passport); //routes inside here cause a ReferenceError: csrfProtection is not defined
http.createServer(app).listen(port);
https.createServer(options, app).listen(443, function () {
//foo
});
-- routes.js --
var csrf = require('csurf'), //this needs to go in here
csrfProtection = csrf(); //this needs to go in here
module.exports = function(app, passport) {
app.route('/somepage')
.get(csrfProtection, function(req, res) {
res.render('somepage', { csrfToken: req.csrfToken()});
});
};
-- routes.js end--
For some strange reason csrfProtection remains unknown inside my page routes causing a ReferenceError (see comment inside code). What am I missing?
EDIT:
ignoreMethods
An array of the methods for which CSRF token checking will disabled. Defaults to ['GET', 'HEAD', 'OPTIONS'].
Try and set it to ['HEAD','OPTIONS']
csrfProtection = csrf(
{ cookie: true, ignoreMethods:['HEAD','OPTIONS' ] }
)
The middleware works properly if placed before the cookie parser.But
the session becomes undefined.
If i move the proxy middleware after the cookie parser it does not
proxy requests silently fails without any errors.I tried creating a post request but nothing happens.
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 cors = require('cors');
var redis = require('redis');
var redisClient = redis.createClient();
var RedisStore = require('connect-redis')(session);
var proxy = require('http-proxy-middleware');
var config = require('config');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
var sessionMiddleware = session({
store: new RedisStore({
client:redisClient
}),
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(sessionMiddleware);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
//cookie parser
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/bower_components', express.static(__dirname + '/bower_components'));
app.use(cors());
//proxy middleware
app.use('/api', proxy({
target: 'http://localhost:4000',
changeOrigin: true,
onProxyReq: function (proxyReq, req, res) {
proxyReq.setHeader('USER_ID', req.session.user_id);
proxyReq.setHeader('TOKEN',config.get('token'));
}
}));
app.use('/', index);
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 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;
http-proxy-middleware npm module middleware
app.use('/api', proxy({
target: 'http://localhost:4000',
changeOrigin: true,
onProxyReq: function (proxyReq, req, res) {
proxyReq.setHeader('USER_ID', req.session.user_id);
proxyReq.setHeader('TOKEN',config.get('token'));
}
}));
If you are keeping any parser middlewares, It will format your request, which is not expected by http-proxy-middleware.
We should place proxy middleware before parser middleware or you can try it out.
onProxyReq: function (proxyReq, req, res) {
if (req.body) {
const body = JSON.stringify(req.body)
proxyReq.setHeader('Content-Type', 'application/json')
proxyReq.setHeader('content-length', body.length)
delete req.body
proxyReq.write(body)
proxyReq.end()
}
},
Note: Changes has to be done with respect to content type
My problem is that req.body becomes undefined when I try to render a page.
My app code:
var https = require('https');
var fs = require('fs');
var mongourl = "mongodb://localhost:27017/auntyinda";
var mongoose = require('mongoose');
fs.readdirSync(__dirname + '/models').forEach(function (filename) {
if (~filename.indexOf('.js')) require(__dirname + "/models/" + filename);
});
//var queries = require('./mongoq/query')
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 expressSession = require('express-session');
var passport = require('passport');
var myPass = require('./security/auth')
var routes = require('./routes/index');
//var users = require('./routes/users');
var app = express();
var server = https.createServer({
cert: fs.readFileSync(__dirname + '/my.crt'),
key: fs.readFileSync(__dirname + '/my.key')
},app).listen(4000);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
//app.configure(function(){
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//app.use(require('connect').bodyParser())
app.use(cookieParser());
app.use(expressSession( {
secret: process.env.SESSION_SECRET || 'sonic12',
resave: false,
saveUninitialized: false
}))
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
//});
mongoose.connect(mongourl)
//app.use('/', myPass);
app.use('/', routes);
//app.use('/users', users);
//app.locals.appdata = require("./data.json")
My route code:
router.post('/register', function(req, res, next) {
regcheck(req.body.username, req.body.password, req.body.passwordConfirm, function (error) {
if (error) {
console.log(req.body) //OUTPUT IS WHAT IS EXPECTED. NICE JSON FORMAT.
res.render('register', {
title: 'Register',
classname: 'register',
socialIcons: socialIcons,
isAuthenticated: false,
regdata: req.body,
err: error
})
}
})
})
I want the render to use the regdata object to refill data that was good back into the registration form. But for some strange reason it becomes undefined by the time it reaches the render.
My EJS file contains this line at the top:
<% console.log('Error recieved: '); console.log(err); console.log(regdata); %>
But the output of the console.log(regdata) is undefined. What is happening here? The err prints as it should. Thanks in Advance for your help.
Try this,
<pre><%= regdata %></pre>
I think you are missing out a = somewhere.
Consult the docs.
In my understanding, the way to serve views is to do the following:
app.set('view engine', 'ejs'); // or jade or whatever
app.set('views', __dirname + '/views'); // specify where to find the view files e.g. index.ejs
app.get("/", function(req, res) { res.render('index') });
However, when I check the code here https://github.com/jedireza/drywall/ , which is a boilerplate for node user management, I don't see any routes defined in app.js. But it works fine and if I type the url /signup in browser it will render signup.jade.
Which part, or which middleware is doing the magic of routing?
app.js content:
'use strict';
//dependencies
var config = require('./config'),
express = require('express'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
session = require('express-session'),
mongoStore = require('connect-mongo')(session),
http = require('http'),
path = require('path'),
passport = require('passport'),
mongoose = require('mongoose'),
helmet = require('helmet'),
csrf = require('csurf');
//create express app
var app = express();
//keep reference to config
app.config = config;
//setup the web server
app.server = http.createServer(app);
//setup mongoose
app.db = mongoose.createConnection(config.mongodb.uri);
app.db.on('error', console.error.bind(console, 'mongoose connection error: '));
app.db.once('open', function () {
//and... we have a data store
});
//config data models
require('./models')(app, mongoose);
//settings
app.disable('x-powered-by');
app.set('port', config.port);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
//middleware
app.use(require('morgan')('dev'));
app.use(require('compression')());
app.use(require('serve-static')(path.join(__dirname, 'public')));
app.use(require('method-override')());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser(config.cryptoKey));
app.use(session({
resave: true,
saveUninitialized: true,
secret: config.cryptoKey,
store: new mongoStore({ url: config.mongodb.uri })
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(csrf({ cookie: { signed: true } }));
helmet(app);
//response locals
app.use(function(req, res, next) {
res.cookie('_csrfToken', req.csrfToken());
res.locals.user = {};
res.locals.user.defaultReturnUrl = req.user && req.user.defaultReturnUrl();
res.locals.user.username = req.user && req.user.username;
next();
});
//global locals
app.locals.projectName = app.config.projectName;
app.locals.copyrightYear = new Date().getFullYear();
app.locals.copyrightName = app.config.companyName;
app.locals.cacheBreaker = 'br34k-01';
//setup passport
require('./passport')(app, passport);
//setup routes
require('./routes')(app, passport);
//custom (friendly) error handler
app.use(require('./views/http/index').http500);
//setup utilities
app.utility = {};
app.utility.sendmail = require('./util/sendmail');
app.utility.slugify = require('./util/slugify');
app.utility.workflow = require('./util/workflow');
//listen up
app.server.listen(app.config.port, function(){
//and... we're live
});
The routes are being added here:
//setup routes
require('./routes')(app, passport);
I just moved to express.js 4.8.7 from 3.x.
I am getting error in express 4.x, "req.body" is undefined.
When I google it. I found that, I have to install "body-parser' module. Even after installing "body-parser' module, I am getting "req.body" undefined.
I am not sure what I need to do. Below is my app.js code
var express = require('express')
, path = require('path')
, redis = require("redis")
, mongoose = require('mongoose')
, favicon = require('serve-favicon')
, compression = require('compression')
, bodyParser = require('body-parser')
, methodOverride = require('method-override')
, errorHandler = require('errorhandler')
, cookieParser = require('cookie-parser')
, morgan = require('morgan')
, multer = require('multer')
, session = require('express-session');
var app = express();
var router = express.Router();
router.use(function(req, res, next) {
console.log('%s %s %s', req.method, req.url, req.path);
next();
});
var routes = require('./routes')(app);
mongoose.connect('mongodb://localhost/abc');
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(favicon(__dirname + '/public/img/favicon.ico'));
app.use(morgan('dev'));
app.use(methodOverride());
app.use(session({resave: true, saveUninitialized: true, secret: 'uwotm8'}));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(multer({ dest: './uploads/'}));
app.use(methodOverride('X-HTTP-Method'));
app.use(methodOverride('X-HTTP-Method-Override'));
app.use(methodOverride('X-Method-Override'));
app.use(compression({'threshold': 512}));
app.use(express.static(path.join(__dirname, 'public')));
if ('development' == app.get('env')) {
app.use(errorHandler());
}
app.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Error happends in my router callback function.
app.route('/xhr/abc').post(function (req, res) {
if (req.xhr) {
var language = req.headers["accept-language"];
...
var reqBody = req.body;
...
}
You need to make sure that your routes come after your included middleware, since middleware/routes/etc. are executed in order in Express 4.