如何从expressjs中的另一个api调用api?

时间:2017-07-04 10:09:22

标签: node.js express

我有这样的api:

app.get('/test', (req, res) => {
   console.log("this is test");
});

和另一个api:

app.get('/check', (req, res) => {
   //I want to call "test" api without redirect to it. 
});

我想在“check”api中调用“test”api而不重定向到“test”api,只需在“test”api中执行该功能。 以上是示例代码。因为我不想'从'test'api重写函数到“check”

5 个答案:

答案 0 :(得分:2)

创建一个需要为两个路由执行的公共中间件。

以下是相同的代码段:

app.get('/test', test);
app.get('/check', check, test);

检查测试是共同使用的中间件。

答案 1 :(得分:1)

简单的解决方案是定义一个可以使用两个请求路由调用的方法。

app.get('/test', (req, res) => {
   console.log("this is test");
    callMeMayBe();
});

callMeMayBe()
{
    //Your code here
}

答案 2 :(得分:1)

要“从另一个API调用API”,快速简便的方法是在Express服务器内发送HTTP请求,浏览器永远不会知道发生内部HTTP调用,而不提及页面重定向。这种设计的好处包括:

  1. 无需更改当前的API设计。
  2. 可以使API调用与从浏览器发送的完全相同。
  3. 以下是一个例子:

    var http = require('http');
    
    router.get('/test', function(req, res) {
      res.end('data_from_test');
    });
    
    router.get('/check', function(req, res) {
      var request = http.request({
        host: 'localhost',
        port: 3000,
        path: '/test',
        method: 'GET',
        headers: {
          // headers such as "Cookie" can be extracted from req object and sent to /test
        }
      }, function(response) {
        var data = '';
        response.setEncoding('utf8');
        response.on('data', (chunk) => {
          data += chunk;
        });
        response.on('end', () => {
          res.end('check result: ' + data);
        });
      });
      request.end();
    });
    

    GET /check的结果是:

    check result: data_from_test
    

答案 3 :(得分:1)

首先单独定义/test处理功能 那你有两个选择。

// ========( 1 )====== testHandler as another function =============
// you can call this function where ever you want.
var testHandler = function(req, res){
    //do something
}
app.get('/test', testHandler);

app.get('/check', function(req, res){
  // you can call testHandler function here
  testHandler(req, res);
});

// ========( 2 )======= testHandler as a middleware =================
// if you want to call testHandler before running check handler function.
// 
var testHandler = function(req, res, next){
    //do something
    ...

    next();
}
app.get('/test', testHandler, function(req, res){});

app.get('/check', testHandler, function(req, res){
  // you can call testHandler function here
  testHandler(req, res);
});

答案 4 :(得分:0)

我在expressjs路由中使用了request module

const request = require('request');

router.get('/test', function(req, res, next) {
    res.send('data_from_test');
});

router.get('/check', function(req, res, next) {
    request.get('http://localhost:3000/test');
});

比http.request模块效果更好