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
---------------------^
Expecting 'ID', 'STRING', 'NUMBER', 'BOOLEAN', 'UNDEFINED', 'NULL', 'DATA', got 'INVALID'

Project structure:

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

app.js:

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(require('connect-flash')());
app.use((req, res, next) => {
  res.locals.messages = require('express-messages')(req, res);
  next();
});

// Handle Sessions
app.use(session({
  secret: 'secret',
  saveUninitialized: true,
  resave: true
}));

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

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

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

layout.hbs

<!DOCTYPE html>
<html>
<head>
  <title>{{title}}</title>
</head>
<body>
  {{{messages()}}}
  {{{body}}}
  <a href="/">index</a>
  <a href="/test">test</a>
</body>
</html>

index.hbs

<h3>This is the index</h3>

test.hbs

<h3>This is the index</h3>

package.json

{
  "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 [https://github.com/expressjs/express-messages][1]

Rendering Messages

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

EJS:

<%- messages() %>
Jade:

!= 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();
lrServer.watch(__dirname + '/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;
    app.listen(port);
    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();

app.use(bodyParser.json());
app.use(cors());

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

});

app.post('/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(req.body.email == users[i].email && req.body.password == users[i].password) {
                    console.log("matched");

                    var currentUser = users[i];
                    res.send({
                        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: ' + req.user.id)
})

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: ' + req.user.id)
})

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

middleware/auth.js

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);
    }
  });

  passport.use(strategy);

  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 socket.io module (below)
    var io = require("socket.io").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){
        response.render("index");
    })
};

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

<!DOCTYPE HTML>
<html lang ="en US">
<head>
    <meta charset="UTF-8">
    <title>Epic Button Game</title>
    http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js
    /socket.io/socket.io.js
    
        $(document).ready(function (){
           // alert("jquery loaded");
           var socket = io.connect();

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

          // this event will emit to the server to reset the counter into 0
            $('#reset').click(function(){
                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); // 
</head>
<body>
    <center>
        <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>
    </center>
</body>
</html>

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();

app.use(bodyParser.urlencoded());
// 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",
    "socket.io": "^1.7.2"
  }
}

Thanks for in advance for any suggestions.


Source: stackoverflow-javascript