首页 > 解决方案 > 如何在不同路由nodejs的router.post请求中使用router.get请求

问题描述

我在 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;

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

//@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.jspostimportgetrequirejs

解决方案


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

//@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)

}

推荐阅读