Search code examples
javascriptnode.jsexpresshandlebars.jsexpress-handlebars

Express res.render renders the wrong file


I've setup a server to use Handlebars as a view engine. Using res.render on a GET request at the main page renders the page properly, however using res.render to render a page other than the main page renders the same page. Even using res.send will send the main handlebars page but leaving the expressions unchanged.

Here's my code:

const express = require("express");
const subdomain = require("express-subdomain");
const handlebars = require("express-handlebars");
const path = require("path");
const bodyParser = require("body-parser");

const app = express();
const subdomain = express.Router();

app.set("views", path.join(__dirname, "/views/layouts"));
app.set("view engine", "handlebars");
app.engine("handlebars", handlebars({
    "layoutsDir": path.join(__dirname + "/views/layouts")
}));

subdomain.use(bodyParser.json());
subdomain.use(bodyParser.urlencoded({"extended": true}));

subdomain.get("/", (req, res) => {
    res.send("books/index.html");
});

subdomain.get("/books", (req, res) => {
    let data = {};

    res.render("books", data);
});

app.use(express.static("public"));
app.use(subdomain("subdomain", subdomain));

app.get("/index", async (req, res) => {
    let data = {};

    res.render("main", data);
});

server = app.listen(8080, () => {
    console.log("listening to requests on port " + 8080);
});

Obviously I would like to generate a page other than just the main page on my site. What am I doing wrong?


Solution

  • It looks like you are doing twice the same thing

    Instead of:

    app.set("views", path.join(__dirname, "/views/layouts"));
    app.set("view engine", "handlebars");
    app.engine("handlebars", handlebars({
        "layoutsDir": path.join(__dirname + "/views/layouts")
    }));
    

    Maybe

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

    Edited:

    Check the edit, "hbs" instead of "handlebars". I have this on my package.json dependencies "hbs": "~4.0.4", or check github.com/sahat/hackathon-starter por a complete boilerplate