Error in NodeJS next is not a function when using middleware

huangapple go评论57阅读模式
英文:

Error in NodeJS next is not a function when using middleware

问题

错误:运行 app.js 时出现 next 不是一个函数的错误。我该如何解决?
英文:

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

得分: 1

你遇到的错误是因为你定义的中间件函数被作为普通函数调用,而不是在 Express 路由中用作中间件。next 函数由 Express 提供,它允许你将控制传递给链中的下一个中间件函数或路由处理程序。

要使用中间件函数,你需要将它附加到 Express 路由,示例如下:

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

// 中间件
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 running at port 3000");
});
英文:

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");
});

huangapple
  • 本文由 发表于 2023年2月14日 00:41:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75438794.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定