【问题标题】:How to use a router.get request in a router.post request of a differents routes nodejs如何在不同路由nodejs的router.post请求中使用router.get请求
【发布时间】:2020-04-28 10:34:33
【问题描述】:

我在一个 Nodejs 应用程序上工作,我想在一个 POST 请求中获得一个 GET 请求的结果,当这两个请求不在同一个路由中时。

我给你详细解释一下:

我的libellecsv.js route 中有以下代码:

const express = require('express');
const router = express.Router();
const Libellecsv = require('../../models/Libellecsv');

//@route   GET api/libellecsv
//@desc    Return all the libelle of the csv present in the database
//@access  Public
router.get('/', function (req, res, next) {
  Libellecsv.find(function (err, libelle) {
    if (err) {
      res.send(err);
    }
    res.json(libelle);
  });
});

module.exports = router;

我想在我的students.js routes 的post 请求中使用这个get 请求的结果:

//@route   POST api/students
//@desc    Fill the database with the json information
//@access  Public
router.post('/', async (req, res) => {

// HERE I WANT TO PUT THE RESULT OF THE LIBELLECSV GET REQUEST IN A VARIABLE

}

我该怎么做?这当然是一个基本问题,但我找不到解决方案。

感谢您的帮助。

【问题讨论】:

    标签: node.js post import get requirejs


    【解决方案1】:

    您当然可以在您的post-handler 中重用Libellecsv 存储库,尽管我会将它包装在一个承诺中,以免有太多的回调链(当然这也需要一些适当的错误处理) :

    //@route   POST api/students
    //@desc    Fill the database with the json information
    //@access  Public
    router.post('/', async(req, res) => {
        const libelle = await new Promise((resolve, reject) => {
                Libellecsv.find(function (err, libelle) {
                    if (err) {
                        return reject(err);
                    }
                    resolve(libelle);
                });
            });
        // do something with libelle here
        console.log(libelle)
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-15
      • 1970-01-01
      • 2015-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-25
      • 1970-01-01
      相关资源
      最近更新 更多