Every time I launch my express application, I encounter this error message

Encountering a type error with Express Router middleware. See below for the code snippets and error details. Any assistance is appreciated?

The application is functioning properly, but when attempting to access the URL in the browser, the following error is displayed in the console.

Here is the content of my app.js file

app.js

//jshint esversion:6
const express = require('express');
const bodyParser = require('body-parser');

const app = express();
app.use("view engine", "ejs");
app.get("/", function(req, res) {
  // res.send("Hello");
  var today = new Date();
  console.log(date);
  var currentDay = today.getDay();
  var day = "";
  console.log(currentDay);
  if (currentDay === 6 || currentDay === 0) {
    // res.send("yay! it's weekend. ");
    day = "weekend";
  } else {
    day = "weekday";

  }
  res.render("list", {
    kindOfDay: day
  });
});



app.listen(3000, function() {
  console.log("server started at port 3000");
});

Below is list.ejs file structure

list.ejs

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>to do list</title>
  </head>
  <body>
    <h1>It's a <%= kindOfDay %>!</h1>
  </body>
</html>

Error Details:

E:\todoList-v1\node_modules\express\lib\router\index.js:458
          throw new TypeError('Router.use() requires a middleware function but 
    got a ' + gettype(fn))
      ^

TypeError: Router.use() requires a middleware function but got a string    
    at Function.use (E:\todoList-v1\node_modules\express\lib\router\index.js:458:13)
    at Function.<anonymous> (E:\todoList-v1\node_modules\express\lib\application.js:220:21)
    at Array.forEach (<anonymous>)
    at Function.use (E:\todoList-v1\node_modules\express\lib\application.js:217:7)
    at Object.<anonymous> (E:\todoList-v1\app.js:6:5)
    at Module._compile (internal/modules/cjs/loader.js:1133:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1153:10)
    at Module.load (internal/modules/cjs/loader.js:977:32)
    at Function.Module._load (internal/modules/cjs/loader.js:877:14)       
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)

Above error message is what I'm currently facing

Answer №1

Here is a helpful tip:

app.set("view engine", "ejs");

This small change makes a big difference when setting express variables. While app.use is used to apply middleware functions, app.set is specifically for setting variables in Express. Remember this distinction to avoid errors in your code!

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

Utilize Javascript to convert centimeters into inches

Can anyone help me with a JavaScript function that accurately converts CM to IN? I've been using the code below: function toFeet(n) { var realFeet = ((n*0.393700) / 12); var feet = Math.floor(realFeet); var inches = Math.round(10*((realFeet ...

What are the steps for integrating connect-multiparty into route paths?

I am looking to incorporate connect-multiparty into my routes. Upon researching, I found the following example... var multipart = require('connect-multiparty'); var multipartMiddleware = multipart(); app.post('/upload', multipartMiddle ...

I want to include an API key query parameter in all my external requests

My express server utilizes an external API, and for each request to that API endpoint ('/api/*'), I want to automatically append a query parameter to the URL without having to manually specify it every time. app.use(function(req, res) { req. ...

How to retrieve the first option selected in Material-UI React?

Hey there! I am currently working with React Material UI select. I have a question - how can I set the first option of items as selected without triggering the onChange method? When I change an option, it triggers the onChange method and adds an attribut ...

Using infoWindows with multiple markers in Google Maps

i have developed a custom Google Maps application that pulls data from a CSV file. The functionality works well, but I am facing an issue with the infoWindow when looping through all the objects. It seems like the problem stems from the marker variable bei ...

Struggle with comparing strings in different cases

When utilizing the "WithText" function within a Testcafe script, it appears to be case-sensitive. How can I modify it to be case-insensitive? For example, allowing both "Myname" and "myname" for a user input. It's problematic when a script fails due t ...

Autonomous library on NPM that verifies requests using a Swagger file

Our team is currently developing APIs using a combination of Swagger, AWS API Gateway, and Lambda functions with NodeJS. While the API gateway handles request validation, our design requires that the lambda functions also validate the request object as an ...

Encountered an error while executing findByIdAndRemove operation

Could someone please assist in identifying the issue with the mongoose findByIdAndRemove function in the delete route provided below? //DELETE Route app.delete("/blogs/:id", function(req, res){ //Delete blog Blog.findByIdAndRemove(req.params.id, funct ...

Pictures failing to load in the MongoDB collection

I am facing an issue with uploading a form that includes an image to my mongodb database. While all the data is being stored correctly, the images are not visible in the database. I suspect this might be related to the error message 'typeError cannot ...

Is it possible to implement reusable test steps in nightwatch.js?

My goal is to develop reusable components for my nightwatch.js tests. For example, logging in and logging out of the web application. What would be the most effective approach or pattern for creating these steps in a way that is reusable? ...

The generation of a JWT is not possible in Node

Currently, I am utilizing the jsonwebtoken library to create a jwt token. Below is my user model structure: const userSchema = new mongoose.Schema({ username: { type: String, required: true, }, password: { type: String, required: tru ...

Challenges Arising from Cross-Origin Resource Sharing in Google Authentication

I've been incorporating Google Auth into my MERN stack web application. Unfortunately, I ran into an issue: When trying to connect to 'http://localhost:5000/api/v1/auth/google' from 'http://localhost:5173', the request was blocked ...

Error encountered in Angular 7.2.0: Attempting to assign a value of type 'string' to a variable of type 'RunGuardsAndResolvers' is not allowed

Encountering an issue with Angular compiler-cli v.7.2.0: Error message: Types of property 'runGuardsAndResolvers' are incompatible. Type 'string' is not assignable to type 'RunGuardsAndResolvers' This error occurs when try ...

I'm currently in the process of creating a snake game using HTML5. Can you help me identify any issues or problems that

I am experiencing an issue where nothing is appearing on the screen. Below are the contents of my index.html file: <html> <body> <canvas id="canvas" width="480" height="480" style="background-color:grey;"></canvas> <script src=" ...

Issue with the AngularJS build in Yeoman

After setting up Yeoman and Bootstrap for an AngularJS project, I utilized the grunt server command for debugging and coding. However, when I tried using the 'grunt build' command, it generated a dist folder. Unfortunately, when I attempted to ru ...

Unconfigured table for all Cassandra materialized views

I am currently dealing with a unique setup where I have 8 servers connected on a local network, each hosting a Cassandra database. Among these servers, 2 are seed nodes and the others function as regular nodes. When running nodetool status, all nodes appea ...

Step-by-step guide on integrating async and await functionality into Vuetify rules using an ajax call

I'm currently using Vuetify form validation to validate an input field, and I'm exploring the possibility of making an ajax get call await so that I can utilize the result in a rule. However, my attempts at this approach have not been successful! ...

Issues with jQuery autocomplete when using special characters (Norwegian)

On my website in Norway, I am facing an issue with jQuery's autocomplete function. When users type in the Norwegian characters æ, ø, and å, the autocomplete feature suggests words with these characters within them but not ones that start with these ...

Here is a unique version: "Dealing with Node.js ES6 (ESM) Modules in TypeScript can be tricky, especially when the TypeScript Compiler (TSC) fails to emit the

I am facing an issue while transpiling my TypeScript project to JavaScript. I have set the project to resolve as an ES6 Module (ESM) by using the "module":"ES6" configuration, but the problem persists. This is the current setup in my ...

Issue with Material-UI Nested Checkbox causing parent DOM to not update upon selection changes

Currently, I am integrating a nested checkbox feature from a working example into my application. The functionality of the checkboxes covers seven different scenarios: - Scenario - No children, no parent selected - Select the parent -> select both pa ...