1

When I try and use <% include ./partials/messages %>, <%= include ./partials/messages %>, or even <%= include ./partials/messages { %>, among my file that contains

<!-- REGISTER.EJS -->

<div class="row mt-5">
    <div class="col-md-6 m-auto">
        <div class="card card-body">
            <h1 class="text-center mb-3">
                <i class="fas fa-user-plus"></i> Register
            </h1>
            <% include ./partials/messages %>
            <form action="/users/register" method="POST">
                <div class="form-group">
                    <label for="name">Name</label>
                    <input
                        type="name"
                        id="name"
                        name="name"
                        class="form-control"
                        placeholder="Enter Name"
                        value="<%= typeof name != 'undefined' ? name : '' %>"
                    />
                </div>
                <div class="form-group">
                    <label for="email">Email</label>
                    <input
                        type="email"
                        id="email"
                        name="email"
                        class="form-control"
                        placeholder="Enter Email"
                        value="<%= typeof email != 'undefined' ? email : '' %>"
                    />
                </div>
                <div class="form-group">
                    <label for="password">Password</label>
                    <input
                        type="password"
                        id="password"
                        name="password"
                        class="form-control"
                        placeholder="Create Password"
                        value="<%= typeof password != 'undefined' ? password : '' %>"
                    />
                </div>
                <div class="form-group">
                    <label for="password2">Confirm Password</label>
                    <input
                        type="password"
                        id="password2"
                        name="password2"
                        class="form-control"
                        placeholder="Confirm Password"
                        value="<%= typeof password2 != 'undefined' ? password2 : '' %>"
                    />
                </div>
                <button type="submit" class="btn btn-primary btn-block">
                    Register
                </button>
            </form>
            <p class="lead mt-4">Have An Account? <a href="/users/login">Login</a></p>
        </div>
    </div>
</div>

I receive the follow error "SyntaxError: Unexpected token / in .... while compiling ejs". I am using this to add immediate feedback to users who try and register such as "password invalid" or "email already exist." I believe I have my messages.ejs file set up correctly as such:

<% if(typeof errors != 'undefined') { %>
<% errors.forEach(function(error) { %>
  <div class="alert alert-warning alert-dismissible fade show" role="alert">
    <%= error.msg %>
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
<%}); %>
<% } %>

<% if(success_msg != '') { %>
  <div class="alert alert-success alert-dismissible fade show" role="alert">
    <%= success_msg %>
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
<% } %>

<% if(error_msg != '') { %>
  <div class="alert alert-warning alert-dismissible fade show" role="alert">
    <%= error_msg %>
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
<% } %>

<% if(error != '') { %>
  <div class="alert alert-warning alert-dismissible fade show" role="alert">
    <%= error %>
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
<% } %>

I am pretty lost. I believe I have added the const example = require('example'); files correctly. My app.js file looks like

const express = require('express');
const expressLayouts = require('express-ejs-layouts');
const mongoose = require('mongoose');
const flash = require('connect-flash');
const session = require('express-session');
const passport = require('passport');

const app = express();

// Passport Config
require('./config/passport')(passport);

// DB Config
const db = require('./config/keys').mongoURI;

// Connect to MongoDB
mongoose
  .connect(
    db,
    { useNewUrlParser: true }
  )
  .then(() => console.log('MongoDB Connected'))
  .catch(err => console.log(err));

app.use(express.static( 'public' ));

// EJS
app.use(expressLayouts);
app.set('view engine', 'ejs');

// Bodyparser 
app.use(express.urlencoded({ extended: false }));

// Express Session
app.use(session({
  secret: 'secret',
  resave: true,
  saveUninitialized: true
}))

// Passport Middleware
app.use(passport.initialize());
app.use(passport.session());

// Connect Flash
app.use(flash());

// Global Variables
app.use((req, res, next) => {
  res.locals.success_msg = req.flash('success_msg');
  res.locals.error_msg = req.flash('error_msg');
  res.locals.error = req.flash('error');
  next();
});

// Routes
app.use('/', require('./routes/index'));
app.use('/users', require('./routes/users'));

const PORT = process.env.PORT || 5000;

app.listen(PORT, console.log(`Server started on port ${PORT}`));

My file structure looks like:

>config
     auth.js
     keys.js
     passport.js
>models
     User.js
>node_modules
>public
>routes
     index.js
     users.js
>views
     >partials
        messages.ejs
     dashboard.ejs
     layout.ejs
     login.ejs
     register.ejs
     welcome.ejs
.gitignore
app.js
package-lock.json
package.json
README.md

Does anyone have any ideas?

Error message looks like this:

SyntaxError: Unexpected token / in C:\Users\jreed\Desktop\appproject\views\register.ejs while compiling ejs

If the above error is not helpful, you may want to try EJS-Lint:
https://github.com/RyanZim/EJS-Lint
Or, if you meant to create an async function, pass `async: true` as an option.
    at new Function (<anonymous>)
    at Template.compile (C:\Users\jreed\Desktop\appproject\node_modules\ejs\lib\ejs.js:626:12)
    at Object.compile (C:\Users\jreed\Desktop\appproject\node_modules\ejs\lib\ejs.js:366:16)
    at handleCache (C:\Users\jreed\Desktop\appproject\node_modules\ejs\lib\ejs.js:215:18)
    at tryHandleCache (C:\Users\jreed\Desktop\appproject\node_modules\ejs\lib\ejs.js:254:16)
    at View.exports.renderFile [as engine] (C:\Users\jreed\Desktop\appproject\node_modules\ejs\lib\ejs.js:459:10)
    at View.render (C:\Users\jreed\Desktop\appproject\node_modules\express\lib\view.js:135:8)
    at tryRender (C:\Users\jreed\Desktop\appproject\node_modules\express\lib\application.js:640:10)
    at Function.render (C:\Users\jreed\Desktop\appproject\node_modules\express\lib\application.js:592:3)
    at ServerResponse.render (C:\Users\jreed\Desktop\appproject\node_modules\express\lib\response.js:1012:7)
    at ServerResponse.res.render (C:\Users\jreed\Desktop\appproject\node_modules\express-ejs-layouts\lib\express-layouts.js:77:18)
    at router.get (C:\Users\jreed\Desktop\appproject\routes\users.js:13:43)
    at Layer.handle [as handle_request] (C:\Users\jreed\Desktop\appproject\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\jreed\Desktop\appproject\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\jreed\Desktop\appproject\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\jreed\Desktop\appproject\node_modules\express\lib\router\layer.js:95:5)

Here is my users.js file:

<!-- USERS.JS -->

const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const passport = require('passport');

// User Model
const User = require('../models/User');

// Login Page
router.get('/login', (req, res) => res.render('login'));

// Register Page
router.get('/register', (req, res) => res.render('register'));

// Register Handle
router.post('/register', (req, res) => {
    const {name, email, password, password2} = req.body;
    let errors = [];

    // Check required fields
    if (!name || !email || !password || !password2) {
        errors.push({msg: 'Please enter all fields'});
    }

    // Check passwords match
    if (password != password2) {
        errors.push({msg: 'Passwords do not match'});
    }

    // Check password length
    if (password.length < 6) {
        errors.push({msg: 'Password must be at least 6 characters'});
    }

    if (errors.length > 0) {
        res.render('register', {errors, name, email, password, password2});
    } else { // Validation passed
        User.findOne({email: email}).then(user => {
            if (user) { // User Exists
                errors.push({msg: 'Email is already registered'})
                res.render('register', {errors, name, email, password, password2});
            } else {
                const newUser = new User({
                    name,
                    email,
                    password
                });

                // Hash Password
                bcrypt.genSalt(10, (err, salt) => bcrypt.hash(newUser.password, salt, (err, hash) => {
                    if(err) throw err;
                    // Set password to hashed
                    newUser.password = hash;
                    // Save user
                    newUser.save()
                        .then(user => {
                            req.flash('success_msg', 'Congratulations! You are now registered and can log in.');
                            res.redirect('/users/login');
                        })
                        .catch(err => console.log(err));
                }))
            }
        });
    }

});

// Login Handle
router.post('/login', (req, res, next) => {
    passport.authenticate('local',{
        successRedirect: '/dashboard',
        failureRedirect: '/users/login',
        failureFlash: true
    })(req, res, next);
});

// Logout Handle
router.get('/logout', (req, res) => {
    req.logout();
    req.flash('success_msg', 'You are logged out.');
    res.redirect('/users/login');
});

module.exports = router;
Jared Reed
  • 57
  • 1
  • 5
  • I ran your code on my machine and it works fine. What is the exact error message? Can you trace it to a certain file/line number? Your messages.ejs file as well as the file that includes it are not broken, so something else must be throwing the error I think. – djs Dec 18 '19 at 03:36
  • Thanks for reaching out. This is the exact error I receive `SyntaxError: Unexpected token / in C:\Users\jreed\Desktop\appproject\views\register.ejs while compiling ejs` – Jared Reed Dec 18 '19 at 05:34
  • I checked the console, and this is the error message I receive `Refused to load the font '' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'font-src' was not explicitly set, so 'default-src' is used as a fallback.` – Jared Reed Dec 18 '19 at 05:46
  • There's no line number for the SyntaxError? Knowing the file is pretty good, maybe post the entire contents of register.ejs so I can take a look. Are you loading in an external font somewhere, that console error is strange, but may just be a browser issue and not related to your app. Could be 'Grammarly' if you have that installed: https://stackoverflow.com/a/50672596/5347875 – djs Dec 18 '19 at 06:00
  • I will add the entire error to the original post. I can't seem to add past a certain amount of characters in a comment. Regarding Grammarly, I did try removing the extension as well as try running localhost:5000/users/register in Internet Explorer, but I ran into the same error message. My register.ejs file is the first main block of code you see in the front with the
    s in them.
    – Jared Reed Dec 18 '19 at 06:14
  • Let me see this file: C:\Users\jreed\Desktop\appproject\routes\users.js as well as the entire resgister.ejs file. – djs Dec 18 '19 at 06:17
  • Okay. The register.ejs file is at the top of the code with the
    elements in it, and the users.ejs file, I just added to the bottom of the thread in my original submission.
    – Jared Reed Dec 18 '19 at 06:21

1 Answers1

3

I think I solved it!

<%- include ('partials/messages') %>

I have no idea why that is the only method that works though, trying to research it now.

djs
  • 3,947
  • 3
  • 14
  • 28