Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/hadoop/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js NodeJS:如何创建简单的中间件?_Node.js - Fatal编程技术网

Node.js NodeJS:如何创建简单的中间件?

Node.js NodeJS:如何创建简单的中间件?,node.js,Node.js,我正在使用nodejsv6.5.0。 我是新手,所以我犯了一些错误,希望能得到一些帮助。 我正在尝试编写自己的中间件。 现在,我的代码正在运行: var http = require('http'); http.createServer(function(req, res) { myMiddleware(req, res); }).listen(3000); function myMiddleware(req, res) { res.end('Hello World'); }

我正在使用nodejsv6.5.0。 我是新手,所以我犯了一些错误,希望能得到一些帮助。 我正在尝试编写自己的中间件。 现在,我的代码正在运行:

var http = require('http');

http.createServer(function(req, res) {
    myMiddleware(req, res);
}).listen(3000);

function myMiddleware(req, res) {
    res.end('Hello World');
};
但是,当我将其更改为:

var http = require('http');

http.createServer(myMiddleware(req, res)).listen(3000);

function myMiddleware(req, res) {
    res.end('Hello World');
};
我收到错误“未定义req”。 请有人向我解释为什么会发生这种情况,以及我需要做些什么来修复它? 干杯。

写吧

var http = require('http');

function myMiddleware(req, res) {
    res.end('Hello World');
};

http.createServer(myMiddleware).listen(3000);

您需要将要表达的功能传递给中间件,而不是执行它

在使用中间件时,我们不需要发送请求或响应

var http = require('http');

function myMiddleware() {
      return function(req,res,next) { 
        // do some stuff here 
        next();
      }
  }

http.createServer(myMiddleware).listen(3000);
或者,如果您想在中间件中传递参数,可以这样使用

  var http = require('http');

    function myMiddleware(getparams) {
          return function(req,res,next) { 
            // do some stuff here 
          console.log(getParams)
            next();
          }
      }

http.createServer(myMiddleware(params)).listen(3000);

下一步是将控制传递给下一个方法或下一个中间件。

这是一个JavaScript错误,与节点无关