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

Kei*_*ima 6 node.js express

我有一个这样的api:

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

和另一个api:

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

我想在“check”api中调用“test”api而不重定向到“test”api,只需在“test”api中执行函数即可。上面是示例代码。因为我不想将函数从“测试”api 重写为“检查”

Cha*_*kay 5

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

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

callMeMayBe()
{
    //Your code here
}
Run Code Online (Sandbox Code Playgroud)


sha*_*ncs 5

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

  1. 无需更改当前的 API 设计。
  2. API 调用可以与从浏览器发送的完全一样。

下面是一个例子:

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();
});
Run Code Online (Sandbox Code Playgroud)

结果GET /check将是:

check result: data_from_test
Run Code Online (Sandbox Code Playgroud)