从Node/Express中的另一个路由内调用API端点 [英] Calling an API endpoint from within another route in Node / Express

查看:214
本文介绍了从Node/Express中的另一个路由内调用API端点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个定义了路由(GET)的myRoute.js,我想从另一个路由(api.js)调用api端点,但我不确定执行此操作的正确方法是什么. api.js路由正常工作(下面的图像和代码).

I have myRoute.js with a route (GET) defined and I want to call an api endpoint from another route (api.js), and I'm not sure what the right way to do this is. The api.js route is working properly (image and code below).

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

按预期工作:

myRoute.js

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

I would like when a user goes to localhost:3000/USER_ID that the route definition gets information from the api. Psuedo code below (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});
});

推荐答案

我会为此使用fetch.您可以将someFunction替换为fetch,然后将res.render代码放入.then()中.因此,您将获得以下信息:

I would use fetch for this. You can replace someFunction with fetch, and then put the res.render code in a .then(). So, you would get this:

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

一种更强大的错误处理方法是编写如下代码:

A more robust way with error handling would be to write something like this:

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

理想的方法是将您的代码抽象为一个方法,这样您就不会像The Reason所说的那样自欺欺人.但是,如果您真的想打电话给自己,这将起作用.

The ideal way would be to abstract your code into a method so you aren't calling yourself, as The Reason said. However, if you really want to call yourself, this will work.

这篇关于从Node/Express中的另一个路由内调用API端点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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