代码之家  ›  专栏  ›  技术社区  ›  Ron I

从node/express中的另一个路由中调用api端点

  •  1
  • Ron I  · 技术社区  · 6 年前

    我定义了一个route(get)的myroute.js,我想从另一个route(api.js)调用一个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;  
       });  
    });
    

    按预期工作:

    enter image description here

    我的路线.js

    我希望当用户转到localhost:3000/user_id时,路由定义从api获取信息。下面是psuedo代码(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});
    });
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   Ryan Z    6 年前

    我会用fetch来做这个。你可以替换 someFunction 具有 fetch ,然后将 res.render A中的代码 .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)});
      });
    });
    

    错误处理的一个更健壮的方法是编写如下内容:

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

    理想的方法是将代码抽象成一个方法,这样就不会像原因所说的那样调用自己。不过,如果你真的想打电话给你自己,这是可行的。

        2
  •  4
  •   The Reason    6 年前

    我不确定你的理解是否正确,但无论如何我会尽力帮助你。所以你有一个类似于

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

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

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

    然后在您的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);
    })
    

    在另一条路线上也可以这样做:

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

    似乎很清楚:)