NODEJS 如何通过中间件连接多个 express.method()

NODEJS how to connect several express.method() via middleware

我已经使用 express() 构建了多种方法。为简单起见,我假设我构建了 2 个 POST() 函数,我希望能够自己使用它们,并通过中间件将它们连接起来以供组合使用。

app.post('/create_obj_1' , function (req,res) {
    //create Object_type_1
    // send Object_type_1 via EXTERNAL API to somewhere
    res.json({{ "statusCode": 200, "message": "OK" }
}
app.post('/create_obj_2' , function (req,res) {
    //create Object_type_2
    // send Object_type_2 via EXTERNAL API to somewhere
    res.json({{ "statusCode": 200, "message": "OK" }
}

我想要一个新的 POST() 可以同时调用其他 2 个(但仍支持独立调用原始 2 我认为通过中间件是可能的,但我不确定如何 - 这就是我认为新的 POST() 应该看起来像 -

app.post('/create_obj_all' , function (req,res) {
   //I want to invoke the create_obj_1 & create_obj_2 , check all OK, and finish
    res.json({{ "statusCode": 200, "message": "OK" }
}

我不确定在这种情况下如何使用中间件。

最重要的是 - 如何连接它们以相互使用资源?假设我想在 obj_2 post() 函数中使用来自 obj_1 创建的外部 API returns 一些值..

我尝试在 middlware_1 -

中使用 request() 的伪代码
var middle_1 = function (req, res, next) {
        req.middle_1_output  = {
            statusCode : 404,
            message : "fail_1"
        }
        var options = { 
                method: 'PUT', url: `EXTERNAL_API`, headers: 
                { 
                    'cache-control': 'no-cache',
                    'content-type': 'application/x-www-form-urlencoded',
                    apikey: `KEY`
                }
            };
        request(options, function (error, response, body) {
            if (error) throw new Error(error);

            // CODE THAT DO SOMETHING AND GET INFORMATION

            // OLD WAY OF res.send here , to allow using in post.POST() was - res.status(200).send(body);

            //res.status(200).send(body);
            req.middle_1_output.statusCode = 200;
            req.middle_1_output.message = "hello world";
        });
     next(); // trigger next middleware
}

鉴于当前示例,我认为您无法做到,除非您稍微调整前两条路由的中间件:

var middleware1 = function(req, res, next) {
  //create Object_type_1
  // send Object_type_1 via EXTERNAL API to somewhere

  next(); // calling next() triggers the next middleware
};

var middleware2 = function(req, res, next) {
  //create Object_type_2
  // send Object_type_2 via EXTERNAL API to somewhere

  next(); // calling next() triggers the next middleware
};

/**
 * This middleware is only used to send success response
 */
var response_success = function(req, res) {

    res.json({ "statusCode": 200, "message": "OK" });
}

app.post('/create_obj_1', middleware1, response_success);

app.post('/create_obj_2', middleware2, response_success);

app.post('/create_obj_all', middleware1, middleware2, response_success);

注意这是我根据您的示例制作的非常简单的解决方案。实际实现将取决于每个中间件期望的输入以及它们生成的输出。同样与此处不同的是,可能还有不同的中间件用于发送响应。

第二部分 解决你问题的第二部分,如果我猜对了你想要将输出从 middleware1 传递到 middleware2。在调用 next(); 之前,您可以简单地将输出附加到 req 对象。像这样:

var middleware1 = function(req, res, next) {

  // do something

  some_external_api_call(function(error, data) {

    if (error) {
      // handle the error yourself or call next(error);
    } else {

      req.middleware1_output = data; // set the output of the external api call into a property of req
      next();
    }
  });
};

var middleware2 = function(req, res, next) {

  // check to see if the middleware1_output has been set 
  // (meaning that the middleware has been called from /create_obj_all )
  if (req.middleware1_output) {

    // do something with the data

  } else {

    // handle scenario when /create_obj_2 is called by itself

  }

  next(); // calling next() triggers the next middleware
};

请注意您必须如何考虑从 POST /create_obj_all 或直接从 POST /create_obj_2.

调用 middleware2 的两种情况

第三部分 您应该从回调中调用 next。看我上面的例子。这是由于 javascript 的 asynchronous/non-blocking 性质。

function middleware(req, res, next) {

    // do something

    call_1st_external_api(some_options, function(error, data) {

        // executed after call_1st_external_api completes

        req.output_of_1st_external_api = data; // store the data of this api call for access from next middleware

        next(); // calls the next middleware

        // nothing here will be executed as next has already been called
    });

    // anything here will be executed before call_1st_external_api is completed
    next(); // this will call the next middleware before call_1st_external_api completes
}

要在同一个中间件中处理两个外部 API,您必须将它们嵌套(或使用异步或承诺):

function middleware(req, res, next) {

    // do something

    call_1st_external_api(some_options, function(error1, data1) {

        // executed after call_1st_external_api completes

        req.output_of_1st_external_api = data1; // store the data of this api call for access from next middleware

        // executed after call_2nd_external_api completes

        call_2nd_external_api(some_options, function(error2, data2) {

            req.output_of_2nd_external_api = data2; // store the data of this api call for access from next middleware

            next();
        });

        // anything here will be executed before call_2nd_external_api is completed
    });

    // anything here will be executed before call_1st_external_api is completed
}

您必须像我在 第二部分 中显示的那样处理上面的所有错误,为了简单起见,我没有在上面的示例中显示。