英文:
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");
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论