NODEJS如何通过中间件连接多个express.method() [英] NODEJS how to connect several express.method() via middleware

查看:85
本文介绍了NODEJS如何通过中间件连接多个express.method()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have built , using express() , a variety of methods. for simplicity let's I assume I built 2 POST() functions and I want to be able to use them by themselves and also to concatenate them via middleware for combine usage.

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的独立调用) 我认为可以通过中间件来实现,但是我不确定如何-这就是我认为新的POST()应该看起来像的样子-

I want to have a new POST() that can invoke both of the other 2 (but still support stand alone invoking of the original 2 I think it's possible via middleware but I am not sure how - this is how I thought the new POST() should look like -

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

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

I am not sure how to approach the middleware usage in such case.

在顶部-如何连接它们以互相使用res?假设EXTERNAL API从obj_1创建中返回了一些值,我想在obj_2 post()函数中使用它..

On top - how can I connect them to use one each other res? let's say the EXTERNAL API returns some value from obj_1 creation which I want to use in obj_2 post() function..

我尝试在middlware_1内部使用request()的伪代码-

a Pseudo code of my attempt to use request() inside the middlware_1 -

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
}

推荐答案

以当前示例为例,除非您对前两条路径的中间件进行一些调整,否则我认为您无法做到:

Given the current example, I don't think you can do it unless you tweak the middlewares for the first two routes a bit:

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

注意,这是我从您的示例中得出的非常简单的解决方案.实际的实现将取决于每个中间件期望什么输入以及它们产生什么输出.与这里不同的是,可能还存在用于发送响应的不同中间件.

Note that this is a very simplistic solution that I made from your example. The actual implementation will depend on what input each middleware is expecting and what output they generate. Also unlike here, there may also be different middlewares for sending the response.

第二部分解决您问题的第二部分,如果我正确地理解了您的信息,则希望将输出从middleware1传递到middleware2.您可以在调用next();之前简单地将输出附加到req对象.像这样:

2nd Part Addressing the second part of your question, if I have got you correctly you want to pass the output from middleware1 to middleware2. You can simply attach the output to the req object before calling next();. Like so:

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的两种情况,您都必须承担责任.

Notice how you have to account for both scenarios where middleware2 is called from POST /create_obj_all or directly from POST /create_obj_2.

第三部分,您应该在回调中调用next.参见我上面的示例.这是由于javascript的异步/非阻塞性质.

3rd Part You should call next from within the callback. See my above example. This is due to the asynchronous/non-blocking nature of javascript.

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,您必须将它们嵌套(或使用async或promises):

To handle two external APIs in the same middlewares you have to nest them (or use async or promises):

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
}

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

You have to handle all the errors above like I've shown in the 2nd Part which I have not shown in the above example for the sake of simplicity.

这篇关于NODEJS如何通过中间件连接多个express.method()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆