node.js - 如何在不同路由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
}
我怎样才能做到这一点 ?这当然是一个基本问题,但我找不到解决方案。
谢谢您的帮助。
解决方案
您当然可以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)
}
推荐阅读
- delphi - 释放表单时访问冲突
- hive - Hive 客户端安装失败
- spring - AspectJ LTW(编织)不适用于 Spring Boot
- pdf - 如何在没有元数据(即创建时间)的 Office 文档中使用 Add-in 程序获取数据?
- java - JFR 显示 Lmax-Disruptor 引擎内的 CPU 利用率很高
- swift - 在子类中调用例程
- jenkins - SonarQube 扫描仪在 Jenkins 日志中发送垃圾邮件 401 错误
- c# - 在 ASP Net.Core 2.2 中使用自动属性扩展 AnchorTagHelper
- time-series - ACF & PACF 图的解释
- react-native - 'keyboardDidHide' 返回 null 而不是对象