node.js - 为什么这个 next() 函数在控制台中打印它的参数?

标签 node.js express

我是 Node 和 Express 的新手,正在学习这些东西。我正在以下链接阅读 Express 的文档:https://expressjs.com/en/guide/routing.html在此页面的路由处理程序部分中,显示:

You can provide multiple callback functions that behave like middleware to handle a request. The only exception is that these callbacks might invoke next('route') to bypass the remaining route callbacks.

本页给出的示例不包含任何带参数的 next()

我尝试实现它并在该函数中传递一些路径作为参数,但它的行为很奇怪,并在控制台中打印该参数并将其发送到浏览器。
下面是我的代码:

const express = require('express');
const port = 8000;
const app = express();

app.get('/', (req, res, next) => {
    console.log("I am the first one");
    next('/demo');
}, function(req, res, next){
    console.log("I am the second one");
});

app.get('/demo', (req, res) => {
    console.log("Good!");
});

app.listen(port, (err) => {
    if(err){
        console.log("ERROS: ",err);
    }
    console.log("Express server is runnig on port: ",port);
});

在浏览器中,我输入http://localhost:8000/
控制台中的输出是:

I am the first one
/demo

next('/demo') 函数调用不会导致 /demo 路由处理程序运行。

我哪里出错了?
我说得对吗?
实际上我无法理解这个参数如何与 next() 函数一起使用。

由于文档页面没有任何在函数中使用参数的示例,任何人都可以通过示例解释一下这个 next() 函数如何使用参数吗?

预先感谢您提供的任何帮助

最佳答案

我在这里做了一些深入研究,因为这对我来说很有趣,然后我意识到这只是返回的错误。让我解释一下。

基本上,next()是expressjs特定的功能,用于将控制权传递给下一个功能单元。它不需要字符串参数,除了一个(在下面给出 - 在错误部分之后)。即使在正确初始化它的情况下也是如此。

这是加载页面后网络选项卡中的输出,请检查。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>/demo</pre>
</body>
</html>

NOTE: next('route') will work only in middleware functions that were loaded by using the app.METHOD() or router.METHOD() functions.

您无法按照目前的方式调用另一台路由器,http 对于关闭 channel 的一个请求将有一个响应。不过你可以做类似的事情。

app.get('/', (req, res, next) => {
    console.log("I am the first one");
    next();
}, function(req, res, next){
    console.log("I am the second one");
    next();
});
app.get('/', (req, res, next) => {
    console.log("I am the third one");
    next();
}, function(req, res, next){
    console.log("I am the fourth one");
});

这里的中间件发挥了它的魔力,它匹配任何相同的路由参数,然后继续执行它。

关于node.js - 为什么这个 next() 函数在控制台中打印它的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60594768/

相关文章:

javascript - 如何使用 JavaScript 编写 NeoVim 插件?

javascript - 如何在不使用 Express 的情况下将 Node 应用程序部署到 heroku

javascript - Mongoose 异步多次保存冲突

node.js - 使用 JSBarCode 创建条形码

node.js - 如何更新存储在排序集中的 Redis 中的元素?

node.js - POST 400(错误请求)JSON 中位置 1 处出现意外标记 o

javascript - 如何使用 spotify web api 获取用户的播放列表列表?

javascript - 如何在 WebStorm 10 中通过 Gulpfile 调试由 nodemon 启动的 Express 应用程序?

javascript - 如何将页面加载后计算出的数据发送到 MongoDB?

node.js - 错误 : Route. get() 需要回调函数,但得到了 [对象未定义]