从 Node / Express 中的另一个路由中调用 API 端点

Ron*_*n I 3 node.js express

我的 myRoute.js 定义了一个路由 (GET),我想从另一个路由 (api.js) 调用 api 端点,但我不确定这样做的正确方法是什么。api.js 路由工作正常(图片和代码如下)。

api.js

router.get('/getGroups/:uid', function(req, res, next) {    
  let uid = req.params.uid;
  db.getAllGroups(uid).then((data) => {
    let response =[];
    for (i in data) {
      response.push(data[i].groupname);
    }
    res.status(200).send(response);
   })
   .catch(function (err) {
     return err;  
   });  
});
Run Code Online (Sandbox Code Playgroud)

按预期工作:

在此处输入图片说明

myRoute.js

我希望当用户访问 localhost:3000/USER_ID 时,路由定义从 api 获取信息。下面的伪代码(someFunction)。

router.get('/:uid', function(req, res, next) {
  let uid = req.params.uid;
  let fromApi = someFunction(`localhost:3000/getAllGroups/${uid}`); // <--!!!
  console.log(fromApi) ;  //expecting array
  res.render('./personal/index.jade', {fromApi JSON stringified});
});
Run Code Online (Sandbox Code Playgroud)

The*_*son 5

不确定我是否理解正确,但无论如何我会尽力提供帮助。所以你有一个像

router.get('/getGroups/:uid', function(req, res, next) {    
  let uid = req.params.uid;
  db.getAllGroups(uid).then((data) => {
    let response =[];
    for (i in data) {
      response.push(data[i].groupname);
    }
    res.status(200).send(response);
   })
   .catch(function (err) {
     return err;  
   });  
});
Run Code Online (Sandbox Code Playgroud)

如果你想重用它,你可以从上面的代码中提取一个函数,如下所示:

async function getAllGroupsByUserId(uid){
  const result = [];
  try{
    const data = await db.getAllGroups(uid);
    for (i in data) {
      result.push(data[i].groupname);
    };
    return result;
  }
  catch(e) {
    return e;
  }
}
Run Code Online (Sandbox Code Playgroud)

然后在你的 api 和任何你想要的地方重用它:

router.get('/getGroups/:uid', async function(req, res, next) {    
  const uid = req.params.uid;
  const groups = await getAllGroupsByUserId(uid);
  res.status(200).send(groups);
})
Run Code Online (Sandbox Code Playgroud)

您可以在另一条路线中做同样的事情:

router.get('/:uid', async function(req, res, next) {
  const uid = req.params.uid;
  const fromApi = await getAllGroupsByUserId(uid); // <--!!!
  console.log(fromApi) ;  //expecting array
  res.render('./personal/index.jade', {fromApi JSON stringified});
});
Run Code Online (Sandbox Code Playgroud)

看起来很清楚:)


Rya*_*n Z 4

我会为此使用 fetch。您可以替换someFunctionfetch,然后将res.render代码放在.then(). 所以,你会得到这个:

const fetch = require("node-fetch");

router.get('/:uid', function(req, res, next) {
  let uid = req.params.uid;
  fetch('localhost:3000/getAllGroups/${uid}').then(res => res.json()).then(function(data) {
    returned = data.json();
    console.log(returned);  //expecting array
    res.render('./personal/index.jade', {JSON.stringify(returned)});
  });
});
Run Code Online (Sandbox Code Playgroud)

一种更可靠的错误处理方法是编写如下内容:

const fetch = require("node-fetch");

function handleErrors(response) {
  if(!response.ok) {
    throw new Error("Request failed " + response.statusText);
  }
  return response;
}

router.get('/:uid', function(req, res, next) {
  let uid = req.params.uid;
  fetch('localhost:3000/getAllGroups/${uid}')
  .then(handleErrors)
  .then(res => res.json())
  .then(function(data) {
    console.log(data) ;  //expecting array
    res.render('./personal/index.jade', {JSON.stringify(data)});
  })
  .catch(function(err) {
    // handle the error here
  })
});
Run Code Online (Sandbox Code Playgroud)

理想的方法是将代码抽象为一个方法,这样您就不会调用自己,正如 The Reason 所说。但是,如果您确实想给自己打电话,这也可以。