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
Related
I have defined express-myconnection database connection in app.js now i want to use that database connection in models like tasks.js how do I implement that connection in models also.Please suggest me better option.
app.js
var createError = require('http-errors');
var express = require('express');
var session = require('express-session');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
// var passport = require('passport');
var cors=require('cors');
var flash = require('connect-flash');
var mysql = require('mysql');
// require('./config/passport')(passport);
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var Tasks=require('./routes/Tasks');
var app = express();
var customers = require('./routes/customers');
var login = require('./routes/login');
var connection = require('express-myconnection');
// view engine setup
// app.set('port', process.env.PORT || 4300);
app.engine('pug', require('pug').__express);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// app.use(passport.initialize());
app.use(session({
secret: 'justasecret',
resave:true,
cookie: {
httpOnly: true,
maxAge : 10000,
},
saveUninitialized: true
}));
/*------------------------------------------
connection peer, register as middleware
type koneksi : single,pool and request
-------------------------------------------*/
// app.use(
// connection(mysql,{
// host: 'localhost',
// user: 'root',
// password : '',
// port : 3306, //port mysql
// database:'nodejs'
// },'pool')
// );//route index, hello world
dbOptions = {
host: 'localhost',
user: 'root',
password: '',
port: 3307,
database: 'nodejs'
};
// const db = mysql.createPool(dbOptions);
app.use(connection(mysql, dbOptions, 'pool'));
app.use(cors());
app.use(logger('dev'));
// app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(flash());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/customers', customers);
app.use('/admin',login);
app.use('/tasks',Tasks);
// require('./routes/login.js')(app, passport);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// 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;
inside models/tasks.js=>
var Task={
getAllTasks:function(callback){
return db.query("Select * from task",callback);
},
getTaskById:function(id,callback){
return db.query("select * from task where Id=?",[id],callback);
},
addTask:function(Task,callback){
return db.query("Insert into task values(?,?,?)",[Task.Id,Task.Title,Task.Status],callback);
},
deleteTask:function(id,callback){
return db.query("delete from task where Id=?",[id],callback);
},
updateTask:function(id,Task,callback){
return db.query("update task set Title=?,Status=? where Id=?",[Task.Title,Task.Status,id],callback);
}
};
module.exports=Task;
express-myconnection extends request object with getConection(callback) function, this way connection instance can be accessed anywhere in routers during request/response life cycle:
// myroute.js
...
module.exports = function(req, res, next) {
...
req.getConnection(function(err, connection) {
if (err) return next(err);
connection.query('SELECT 1 AS RESULT', [], function(err, results) {
if (err) return next(err);
results[0].RESULT;
// -> 1
res.send(200);
});
});
...
}
...
I am trying to print out a session object in middleware of an ExpressJS framework. I am new to a session with express and want to see if the object saves to Redis which I have configurated in the app.js file
[index.js (router)]
router.use('/', function(req, res, next) {
req.session.user = {};
req.session.user.browserInformation = req.headers['user-agent'];
console.log(req.session);
next();
});
router.get('/', function(req, res, next) {
res.render('index.html');
});
[The app.js File:]
'use strict';
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const bodyParser = require('body-parser');
const session = require('express-session');
const redis = require('redis');
const redisStore = require('connect-redis')(session);
const client = redis.createClient();
const app = express();
const _Utils = require('./application/_Utils');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
extended: false
}));
app.use(cookieParser());
app.use(bodyParser.urlencoded({
extended: false
}))
app.use(bodyParser.json())
app.use(express.static(path.join(__dirname, 'views')));
//require('./config/router')(app);
let indexRouter = require('./routes/index');
app.engine('html', require('ejs').renderFile)
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// 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');
});
app.use(session({
secret: _Utils.getHashedValue(),
store: new redisStore({
host: '127.0.0.1',
port: 6379,
client: client,
ttl: 3600000
}),
saveUninitialized: false,
resave: false,
cookie: {
expires: new Date(Date.now() + 3600000),
maxAge: 3600000
},
}));
module.exports = app;
An issue I am having is that nothing is printing or Redis is empty when I execute KEYES * command in the terminal client interface
EDIT: Added a whole app.js file
in my case code is worked:
console.log(req.session);
Also use this in attend some information to session use this:
req.session.mail="a#b.com";
İf you are in localhost add this unsecure cookie options in our code. For example:
app.use(session({ secret: 'GttiginYagmurlagelkuskunumyagmuralara' ,resave: true,
saveUninitialized: true,
cookie: { secure: false,maxAge: 3600000}}));
I was trying to write some test which will emulate the post, but I have realised that nothing is posting. After further debugging, I realised that req.body is always undefined. Question is where did I make a mistake and how do I fix it. I seems that the problem is somewhere in the app.js file with order how the middleware loads but I can not figure it out where.
app.js
'use strict';
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const bodyParser = require('body-parser');
const fs = require('fs');
const session = require('express-session');
const redis = require('redis');
const mongoose = require('mongoose');
const redisStore = require('connect-redis')(session);
const client = redis.createClient();
const app = express();
const _UTILS = require('./application/_UTILS');
const db = JSON.parse(fs.readFileSync('/srv/webkb_mean/config/configFiles/database.json', 'utf8'));
mongoose.connect('mongodb://' + db['mongodb']['url'] + '/webKB-main');
mongoose.Promise = global.Promise;
app.use(session({
secret: _UTILS.getHashedValue(),
// create new redis store.
store: new redisStore({
host: 'localhost',
port: 6379,
client: client,
ttl: 36000
}),
saveUninitialized: false,
resave: false
}));
require('./config/router')(app);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
extended: false
}));
app.use(cookieParser());
app.use(bodyParser.urlencoded({
extended: true
}))
app.use(bodyParser.json())
app.use(express.static(path.join(__dirname, 'views')));
app.engine('html', require('ejs').renderFile)
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// 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;
Your adding your bodyParser middleware to your server after you’ve added your routes. This is because express executes middleware(which includes routers since they are also middleware) in the order which they were added via .use().
Just move your router registration line:
require('./config/router')(app);
After your last middleware and before your 404 NOT FOUND handler.
app.engine('html', require('ejs').renderFile)
require('./config/router')(app);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
I am new to NodeJS, I have downloaded my project from github and installed all the required NodeJS modules. and know it just showing
Webstorm console:
run app.js
Process finished with exit code 0
and stops the application.
Why it is getting stop. I cannot access localhost:3000. Your guidance will be highly appreciated.
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 session = require('express-session');
var index = require('./routes/index');
var login = require('./routes/login');
var logout = require('./routes/logout');
var contact = require('./routes/contact');
var signup = require('./routes/signup');
var app = express();
var connection = require('express-myconnection');
var mysql = require('mysql');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(session({
secret: '123secret',
proxy: true,
resave: true,
saveUninitialized: true
}));
app.use(
connection(mysql, {
host: 'localhost',
user: 'proj',
password: '123456',
port: 3306, //port mysql
database: 'projectnode'
}, 'request')
);
// uncomment after placing your favicon in /assets
//app.use(favicon(path.join(__dirname, 'assets', '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, 'assets')));
app.use('/', index);
app.use('/login', login);
app.post('/login', login);
app.post('/signup', signup);
app.get('/contact', contact);
app.post('/contact', contact);
app.get('/logout', logout);
// 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;
I once had this problem before because the Webstorm console was executing app.js instead of www.
Just go to Run/Debug Configurations panel (You can access this from the Navigation Bar):
Navigate to your app.js Configuration tab and then change the path for the JavaScript file to your www file.
I'm trying to get Toastr library to work in my ExpressJS app! I scaffolded the app with the yeoman 'standard' Express Generator...
I've required the lib express-toastr and did the following:
in app.js:
const cookieParser = require('cookie-parser');
const session = require('express-session');
const flash = require('connect-flash');
const toastr = require('express-toastr');
app.use(cookieParser());
app.use(session( {secret: 'xxx', saveUninitialized: true, resave: true} ));
app.use(flash());
app.use(toastr());
in index.js
const express = require('express');
const router = express.Router();
const httpntlm = require('httpntlm');
router.post('/', function (req, res, next) {
// parse inputs
let user = req.body.user || "";
let password = req.body.password || "";
// save in session
req.session.user = {user: user, password: password};
// appropriate response to login attempt
if (!req.session.user) {
res.status(401).send();
}
else {
req.toastr.success('Successfully logged in.', "You're in!");
res.render('groups', {
req: req
});
}
});
module.exports = router;
In index.jade
#{req.toastr.render()}
I'm loading these files in my <head> section:
link(rel='stylesheet', href='//cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.2/css/toastr.min.css')
script(src='/components/jquery/dist/jquery.min.js')
script(src='//cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.2/js/toastr.min.js')
Nothing is showing. What am I missing???
-- UPDATE! --
Here is my complete app.js file. I now try to use express-flash and making a dedicated route for showing a flash message. Still not working. Please help!
'use strict';
const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const expressSanitizer = require('express-sanitizer');
const login = require('./routes/login');
const apply = require('./routes/apply');
const admin = require('./routes/admin');
var session = require('express-session');
var flash = require('express-flash');
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(session({
cookie: { maxAge: 60000 },
store: new session.MemoryStore,
saveUninitialized: true,
resave: 'true',
secret: 'secret'
}));
app.use(flash());
// Route that creates a flash message using the express-flash module
app.all('/express-flash', function( req, res ) {
req.flash('success', 'This is a flash message using the express-flash module.');
res.redirect(301, '/');
});
// sanitize inputs
app.use(expressSanitizer());
app.use('/', apply);
app.use('/apply', apply);
app.use('/login', login);
app.use('/admin', admin);
// 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;
Try using this middleware in your app.js, I found this here
app.use(function (req, res, next)
{
res.locals.toasts = req.toastr.render()
next()
});
and then access locals in your view as follows:
#{toasts}
This worked for me.
So I am not familiar with your syntax in your index.jade file(!=). What does it do? If you change that line in your index to #{req.toastr.render()} it should work.