0

I am following this video to create a simple server in NodeJS (v16.19.0) and ExpressJS (v4.18.2).

app.js

const express = require("express");
const app = express();

// Middleware

const middleware = (req, res, next) => {
  console.log(`Hello my middleware`);
  next();                                   //error on this line: next is not a function
}

middleware();

app.get("/", (req, res) => {
  res.send(`Hello world from server`);
});

app.listen(3000, () => {
  console.log("server runnin at port 3000");
});

error: next is not a function, when I run app.js. How do I solve this

1 Answer 1

1

The error you're encountering is because the middleware function you've defined is being invoked as a regular function, rather than being used as middleware in an Express route. The next function is provided by Express and allows you to pass control to the next middleware function or route handler in the chain.

To use the middleware function, you need to attach it to an Express route as follows:

const express = require("express");
const app = express();

// Middleware
const middleware = (req, res, next) => {
  console.log(`Hello my middleware`);
  next();
};

app.use(middleware);

app.get("/", (req, res) => {
  res.send(`Hello world from server`);
});

app.listen(3000, () => {
  console.log("server runnin at port 3000");
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.