The server is unable to process the .get() request for the file rendering

Struggling with basic Express routing here. I want the server to render 'layout2.hbs' when accessing '/1', but all I'm getting is a 304 in the console.

Here's the error message:

GET / 304 30.902 ms - -
GET /style.css 304 3.370 ms - -
GET /print2.css 304 0.553 ms - -
GET /1 304 9.213 ms - -

This is how my index.js file looks like:

var express = require('express');
var router = express.Router();
var db = require('monk')('localhost:27017/');
var userData = db.get('user-data');
var app = require('express')();

router.get('/', function(req,res,next){
    res.render('layout');
});

router.get('/1', function(req,res,next){
    res.render('layout2');
});

router.use(express.static("public"));

module.exports = router;

The handles in my app.js setup look good:

var express = require('express');
var app = require('express')();
var path = require('path');
var port = require('port');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var hbs = require('express-handlebars');
const queryString = require('query-string');

var routes = require('./routes/index');

var app = express();

// view engine setup
app.engine('hbs', hbs({extname: 'hbs', defaultLayout: 'layout', layoutsDir: __dirname + '/views'}));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

// 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('/', routes);

// 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;

My file structure is as follows:

Bloodborne Backend (project folder)
      │
      |
      |   
    public------print2.css
      |         style.css     
      |           
      | 
      |   
    routes-------index.js
      |
      |
      |
    views-------layout.hbs
      |         layout2.hbs
      |
      |
    app.js
  package.json

I hope you can understand my directory structure. When I try accessing '/1' on localhost, it should load 'layout2.hbs'. Instead, I keep getting a 304 response code and I'm stuck searching for a solution!

Answer №1

Your code is not working for some reason, but there are a few fixes that need to be made.

Make sure the express app is only generated once in the app.js file.

The static folder should only be registered once in the main app.js file.

I've taken the necessary code snippets and created a simple working example based on your directory structure.

projectFolder
  node_modules
    ...
  public
    image.jpg
    style.css
    ...
  routes
    routes.js
    ...
  views
    layout.hbs
    one.hbs
    two.hbs
    ...
  package.json
  app.js

app.js:

const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const hbs = require('express-handlebars');

const router = require('./routes/routes.js' );

const app = express();

app.engine('hbs', hbs({ extname: 'hbs', defaultLayout: 'layout', layoutsDir: __dirname + '/views' }));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use( express.static(path.join(__dirname, 'public')) );

app.use('/', router );

app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: err
  });
});

app.listen( 4444 );

routes.js:

const express = require('express');
const router = express.Router();

router.get('/', function(req,res,next){
  res.render('one' );
});

router.get('/1', function(req,res,next){
  res.render('two');
});

module.exports = router;

layout.hbs:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Default Layout</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    {{{body}}}
    <img src="image.jpg" width="200px">
</body>
</html>

one.hbs

<p> Fragment added from one.hbs </p>

two.hbs

<p> Fragment added from two.hbs </p>

Happy coding!!

Answer №2

@Hitesh Lala successfully resolved the issue by suggesting a modification to my defaultLayout setting in my app.js file, switching it to use an hbs file named index.hbs. Following this change, my index.js file was able to correctly direct to the appropriate hbs files - specifically layout.hbs and layout2.hbs in my case.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error message encountered in MEAN application request

Learning how to use the MEAN stack has been an exciting journey for me as I venture into building web apps. Rather than relying on yeoman generators or npm app to do the heavy lifting of generating code, I have delved into creating my entire app from scrat ...

I need help figuring out how to send a POST/GET request from AJAX to a custom module controller in Odoo 10, but I'm running into issues

I have implemented a custom module in Odoo 10 with a simple controller. Everything works smoothly when accessing http://127.0.0.1:8069/cmodule/cmodule through the browser, displaying the expected return string. However, I encountered an issue when attempt ...

executing ajax request to call a function, encountering partial success and encountering partial failure

Apologies for the lack of clarity in the title. I currently have a search engine that utilizes an ajax function. At present, when I type "t" in the search box, only the tags containing the word "t" are displayed (for example, if I type "t", then "test" sho ...

Searching for the position of different size values according to their specific value

information = { boxNoTo: 1, boxNoFrom: 1, size: 'M', } items = [{ size: 'M', },{ size: 'M', },{ size: 'S,M,L,XS', boxNoTo: 1, boxNoFrom: 1, country: 'CA', name: 'Josh' }] This is what I have don ...

Cassandra encountered a TypeError stating that the "value" argument is exceeding the bounds

I keep encountering the error message below. Any thoughts on what might be causing it? TypeError: "value" argument is out of bounds at checkInt (buffer.js:1041:11) at Buffer.writeInt32BE (buffer.js:1244:5) at Encoder.encodeInt (/ ...

Calculate the total amount from the selected items on the list, depending on the clicked ('active') element

My main objective is to achieve the following: Before any clicks || After the user selects the desired item After conducting some research, I successfully implemented this using vue.js https://jsfiddle.net/Hanstopz/Lcnxtg51/10/ However, I encountered ...

Guiding towards the correct form depending on which button is selected

For my current project, I am utilizing the MEAN stack. I have successfully created multiple registration forms. One of these forms is index.html which utilizes Angular to display various views/tabs within it, making it a multi-paged form. Another registr ...

Middleware for cascading in Mongoose, spanning across various levels in the

I have been working on implementing cascading 'remove' middleware with mongoose for a project. In my database structure, I have nested collections as follows: 'modules' -> 'modulesInst' -> 'assignments' -> ...

When using the `extends layout` node in code, the block content may not be displayed as intended

In a few different projects, I have encountered the same issue. The node app uses express 2.5.8 and jade 0.20.3 (although updating to newer versions of jade and express did not solve the problem). Here is a simple jade layout: "layout.jade" doctype 5 ht ...

Is it possible to use Vue files without relying on NodeJS?

Is it possible to host my app outside of Node.js while still using .vue files and possibly npm as a build system? I don't require backward compatibility, as long as it works on the latest Chrome development version. Are there any examples or tutorial ...

Issue: In an Angular electron app, a ReferenceError is thrown indicating that 'cv' is

I have been working on a face detection app using OpenCv.js within an Angular electron application. To implement this, I decided to utilize the ng-open-cv module from npm modules. However, when attempting to inject the NgOpenCVService into the constructor ...

"The JavaScript code included in the index.html file is not functioning as expected when called in the main.js file within a

Here is the index.html code for a simple VueJS app that includes a widget from netvibes.com. The widget code is added in the html file and functioning properly. <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC " ...

"Encountered a 'NextAuth expression cannot be called' error

Recently, I delved into learning about authentication in Next.js using next-auth. Following the documentation diligently, I ended up with my app/api/auth/[...nextauth]/route.ts code snippet below: import NextAuth, { type NextAuthOptions } from "next-a ...

After downloading the latest version of NodeJS, why am I seeing this error when trying to create a new React app using npx?

After updating to a newer version of NodeJS, I attempted to create a new React app using the command npx create-react-app my-app. However, I encountered the following error message: Try the new cross-platform PowerShell https://aka.ms/pscore6 PS E:\A ...

change the css back to its original state when a key is pressed

Is there a way to retrieve the original CSS of an element that changes on hover without rewriting it all? Below is my code: $(document).keydown(function(e) { if (e.keyCode == 27) { $(NBSmegamenu).css('display', 'none');} ...

Deactivating and activating an HTML input button

So I was tinkering with this cool button: <input id="Button" type="button" value="+" style="background-color:grey" onclick="Me();"/> I've been wondering, how can I conveniently control its state of being disabled or enabled? Initially, I attem ...

Angular 2: How to Avoid Exceeding Maximum Call Stack Size with Eager Loading

I'm facing an issue with preloading all of my child route modules. In my root routing module, I have the following configuration: RouterModule.forRoot(appRoutes, { preloadingStrategy: AppCustomPreloader }) The structure of AppCustomPreloader is as f ...

Prevent elements from displaying until Masonry has been properly set up

My goal is to merge Masonry elements with existing ones. Currently, the items appear before Masonry initializes then quickly adjust into position a moment later. I want them to remain hidden until they are in their proper place. This is the snippet (with ...

Implementing bidirectional data binding with Semantic UI's search dropdown feature in Vue.js

I'm currently facing an issue with the Semantic-UI searchable dropdown and Vuejs data binding. It seems like only one changed option is being model-bound, no matter which dropdown option I select. Here's a snippet of my code. I attempted to use ...