Expressjs, Handlebars(hbs), express-messages, flash-connect. Not able to render flash messages

I’m doing an express app and I’d like to show flash messages when a user registers using a form.

The technologies that I’m using are Node.js, Express.js, Handlebars(hbs), connect-flash and express-messages.

In order to be easier to find the error, I’ve created a new app in the simplest way that I could.

The error is:
Error: /Applications/MAMP/htdocs/hbs-simple/views/index.hbs: Parse error on line 7:
...</head><body> {{{messages()}}} {{{b

Project structure:

├── app.js
├── package.json
└── _views
    ├── index.hbs
    ├── layout.hbs
    └── test.hbs


const express = require('express');
const app = express();
const path = require('path');
const session = require('express-session');
const flash = require('connect-flash');
const hbs = require('hbs');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

app.use((req, res, next) => {
  res.locals.messages = require('express-messages')(req, res);

// Handle Sessions
  secret: 'secret',
  saveUninitialized: true,
  resave: true

app.get('/', (req, res, next) => {
  req.flash('success', 'Rendering index...');

app.get('/test', (req, res, next) => {
  req.flash('success', 'Rendering test...');

app.listen(3000, function () {
  console.log('Listening on port 3000!');


<!DOCTYPE html>
  <a href="/">index</a>
  <a href="/test">test</a>


<h3>This is the index</h3>


<h3>This is the index</h3>


  "name": "hbs-simple",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  "author": "Rafa",
  "license": "ISC",
  "dependencies": {
    "connect-flash": "^0.1.1",
    "express": "^4.15.3",
    "express-messages": "^1.0.1",
    "express-session": "^1.15.3",
    "hbs": "^4.0.1",
    "path": "^0.12.7"

This is from the express-messages documentation that you can find on [][1]

Rendering Messages

Call the messages() function as specified by your rendering engine:


<%- messages() %>

!= messages()

Which using hbs should be {{{messages}}} , but this doesnt work as I expected.

Any ideas or any solution for this situation.

Thanks a lot!

Source: stackoverflow-javascript

Livereload reloads only the first .css file in head

I am setting up Livereload in a Node environment, using Express server and Gulp as my task runner and, finally, using Ejs for my templates.

The issue: I am not able to get all .css reloaded. I only get the first .css file in head bound to the livereload server.

Current set up:

I installed livereload package, and set it up in my index.js file like:

// ...
// index.js

var lr = require('livereload');
var lrServer = lr.createServer(); + '/public');

Note: Right now, all my files are in /public folder. Later I will set them up to a /dist folder.

The express set up is a very basic set up.

// ...
// index.js
// ================================================
// Ejs for my templates/partials
// ================================================
app.engine('.ejs', require('ejs').__express);
app.set('view engine', 'ejs');

// ================================================    
// static files from my currently set static folder
// ================================================
app.use(express.static(path.join(__dirname + '/public')));

// ================================================    
// Express starting on :3000 + istanbul ignore next
// ================================================
if (!module.parent) {
    var port = 3000;
    console.log('Express started on port', port);

Finally, I start my server with nodemon

"#file": "package.json",
"scripts": {
    "start": "nodemon -e js,ejs --watch views index.js",

If everything should be fine, is there an alternative way, without using livereload plugin, to get a Node/Express/Ejs/Gulp environment working with Livereload?

Thank you all for you help.

Source: stackoverflow-javascript

Node throw new Error(‘Can’t set headers after they are sent.’)

I am having the above problem with one of my node calls.
To my knowledge this error shows if you res.send gets called more than once.
Looking at the code it should only send res once so I am not sure what is wrong here.

It throws the error when I insert

        else {
            res.send("Username or Password is wrong");


var express = require('express');
var bodyParser = require('body-parser');
var session = require('express-session');
var cors = require('cors');
var massive = require('massive');
var config = require('./config');
var app = express();


var db = massive.connect({connectionString: config.connectionString}, function(err, localdb){
    db = localdb;
    app.set('db', db);

});'/api/login', function(req, res, next) {

    db.get_users(function(err, users) {
        if(err) res.status(500).json(err);
        else {
            for(var i = 0; i < users.length; i++) {
                if( == users[i].email && req.body.password == users[i].password) {

                    var currentUser = users[i];
                        msg: 'passed',
                        user: currentUser
                else {
                    res.send("Username or Password is wrong");



app.listen(3000, function() {
    console.log("I am listening");

Source: stackoverflow-javascript

Wrapping middleware as a function declaration

I have some middleware which is currently set up as a function that must get invoked in the route handler.

import auth from '../middleware/auth'

userRouter.get('/dashboard', auth().authenticate(), function(req, res) {
  res.send('It worked! User id is: ' +

This causes some problems with the order of execution when I import the route.

I would like to invoke it only when the route gets hit. Something like this (without the ())

import auth from '../middleware/auth'

userRouter.get('/dashboard', auth.authenticate, function(req, res) {
  res.send('It worked! User id is: ' +

How must I write the middleware in order to support this?


module.exports = function() {
  console.log('env, mongo', process.env.JWT_SECRET)
  var options = {};
  options.jwtFromRequest = ExtractJwt.fromAuthHeader()
  options.secretOrKey = 'superdupersecret'

  var strategy = new JwtStrategy(options, function(payload, done) {
    var user = payload._id || null;
    if (user) {
      return done(null, { id: user });
    } else {
      return done(new Error("User not found"), null);


  return {
    initialize: () => {
      return passport.initialize();
    authenticate: () => {
      return passport.authenticate("jwt", { session: false });

I suppose I must pass req, res, next to authenticate, but then how do I pass it to passport.authenticate?

Source: stackoverflow-javascript

Having trouble getting a counter reset function to work using sockets in express

I have a project I am working on for a coding bootcamp. For the project I need to create a website that has a button that when pressed adds +1 to a counter and displays how many times the button has been pressed. The project also needs a reset button that when pressed resets the count back to zero.

I created the project and everything is working well except for the reset function. Whenever I press the reset button nothing happens. I have looked over the code and I don’t see any errors in the reset function that I wrote. Could anyone out there give me any tips on something I may be overlooking as a newbie coder?

Here is my index.js page:

module.exports = function Route (app, server) {
    // this gets the module (below)
    var io = require("").listen(server)

    var counter = 0; //saves the count

    io.sockets.on("connection", function(socket){
        socket.on("push_button", function(data){
            counter +=1;
            io.emit("push_counter", {response: counter}); 
            /* io.emit is a full broadcast, thus sends data to all connectd clients
            will send counter number to index.ejs after increasing by 1 */

        socket.on("reset_counter", function(data){
            counter = 0;
            io.emit("reset_response", {response: counter});
            /* Will set counter to 0 and send to index.ejs */


    // root route to render the index.ejs view (below)
    app.get("/", function(request, response){

Here is my index.ejs file that I have stored in a views folder. This page contains the reset function:

<html lang ="en US">
    <meta charset="UTF-8">
    <title>Epic Button Game</title>
        $(document).ready(function (){
           // alert("jquery loaded");
           var socket = io.connect();

          //lets emit an event when somebody pushes the button
                socket.emit("push_button", {action: "Somebody pushed the button"});

          // this event will emit to the server to reset the counter into 0
                socket.emit("reset_counter", {action: 'Resetting the counter'});

          // listen to the push_counter event from server
          socket.on("push_counter", function (data){
             console.log(data); // 
        <h2 id="message">Reset needs to be fixed!</h2>
        <h4>Push the button to update the count!</h4>
        <button id="push">Push this awesome button</button>
        <button id="reset">Reset Count</button>

Here is my server.js page:

// require express, path, body-parser
var express = require("express");
var path = require("path");
var bodyParser = require('body-parser');
// create the express app
var app = express();

// static content
app.use(express.static(path.join(__dirname, "./static")));
// setting up ejs and our views folder
app.set('views', path.join(__dirname, './views'));
app.set('view engine', 'ejs');
// tell the express app to listen on port 3000
var server = app.listen(3000, function() {
    console.log("listening on port 3000");

//we're going to have /routes/index.js handle all of our routing
var route = require('./routes/index.js')(app, server);

Finally my package.json page which contains a list of dependencies I am using:

  "name": "epic_button_game",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "start": "node server.js"
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "ejs": "^2.5.5",
    "express": "^4.14.1",
    "": "^1.7.2"

Thanks for in advance for any suggestions.

Source: stackoverflow-javascript