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.
Related
I know that I am connecting to 'routes/dropbox' When I call the post inside the router, I get the error "Route.post() requires a callback function but got a [object Object]"
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 helmet = require('helmet');
var cors = require('cors');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var authRouter = require('./routes/auth');
var dbRouter = require('./routes/dropbox');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('combined'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(helmet());
app.use(cors());
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/auth', authRouter);
app.use('/db', dbRouter);
dropbox.js
You can see that I my app.post is set up inside router. The error is occurring when I call that post. Did I write this incorrectly?
var express = require('express');
var router = express.Router();
const dotenv = require('dotenv');
dotenv.config();
var app = express();
router.get('/getAllFolders', function (request, response, next)
{
app.post('https://api.dropboxapi.com/2/files/list_folder',
{
headers:
{
'Content-Type' : 'application/json',
'Authorization' : process.env.DB_AUTH
},
data:
{
'path': '',
'recursive': false,
'include_media_info': false,
'include_deleted': false,
'include_has_explicit_shared_members': false,
'include_mounted_folders': true,
'include_non_downloadable_files': false
}
})
.then(function (r)
{
res.send(r);
})
.catch(function (e)
{
res.send(e);
});
});
module.exports = router;
app is a local express instance. app.post is setting up a local handler for a post request, similar to router.post would.
Use a http client library like axios.
const axios = require('axios');
axios.post('https://api.dropboxapi.com/2/files/list_folder', data, options)
.then(function (r) {
res.send(r);
})
.catch(function (error) {
res.status(500);
res.send(error);
});
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
Am trying to split and merge the uploaded pdf file in nodejs,while am running i getting error" TypeError: Cannot read property 'FileSystem' of undefined","ReferenceError: FS is not defined" help me to fix it.
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 fileUpload = require('express-fileupload');
var routes = require('./routes/index');
var users = require('./routes/users');
var gm = require('gm');
var app = express();
var fs =require('fs');
app.use(fileUpload());
app.post('/upload', function(req, res) {
var sampleFile;
console.log("upload");
if (!req.files) {
res.send('No files were uploaded.');
return;
}
new FS.Store.FileSystem("thumbs", {
transformWrite: function(fileObj, readStream, writeStream) {
gm(readStream, fileObj.name() + '[0]').resize('100', '100').stream('png').pipe(writeStream);
},
beforeWrite: function (fileObj) {
return {
extension: 'pdf',
type: 'pdf'
};
},
path: "./public/images/",
})
sampleFile = req.files.sampleFile;
console.log("statrttttttttt");
console.log(req);
var fileName=sampleFile.name;
sampleFile.mv('./public/images/'+fileName, function(err) {
if (err) {
res.status(500).send(err);
}
else {
res.send("<html><h1><object data='/images/"+fileName+"'</h1></object></html>");
}
});
})
// 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.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('/js',express.static(path.join(__dirname, 'public/javascripts')));
app.use('/', routes);
app.use('/users', users);
module.exports = app;
new FS.Store.FileSystem("thumbs", {
transformWrite: function(fileObj, readStream, writeStream) {
gm(readStream, fileObj.name() + '[0]').resize('100', '100').stream('png').pipe(writeStream);
},
javascript is case senesitive. you are referencing to fs module as:
var fs = require('fs');
and using FS.
I have this initialisation code;
app.use(cookieParser);
var redis = require('redis');
var redisOptions = {}
redisOptions.client = redis.createClient(<removed>, 'pub-redis-12124.us-east-1-2.3.ec2.garantiadata.com');
app.use(session({
store: new RedisStore(redisOptions),
secret: 'keyboard cat',
resave: true,
saveUninitialized: true
}));
In my routing, I have this;
router.post('/login', function (req, res) {
var users = req.db.get('users');
users.findOne({email: req.body.email}, function (err, user) {
console.log(user);
if (req.body.password == user.password) {
req.session.id = user._id;
console.log("id:" );
res.send('successful login' + req.session.id);
} else {
// Make sure to log failed auth requests
var log = req.db.get('failed_auth');
var fail_info = {};
fail_info.email = req.body.email;
fail_info.ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
fail_info.timestamp = Date.now();
log.insert(fail_info, function(doc) {
res.send('bad creds');
});
}
});
});
However when I try to go through this code, I get this error;
TypeError: Cannot set property 'id' of undefined
My Redis server is one of the free hosted ones from redislabs. I'm not sure if I need to authenticate although I don't think that I do. Any tips on the way forward?
edit:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var bodyParser = require('body-parser')
var cookieParser = require('cookie-parser')();
var session=require('express-session');
var RedisStore = require('connect-redis')(session);
// New Code
var monk = require('monk');
var db = monk('localhost:27017/manpoints');
var routes = require('./routes/index');
var account = require('./routes/account')
var app = express();
// 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(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
Ignore the mess/unused stuff, I've been trying lots of different things trying to get this to work.
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);