我在一个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
-处理程序,不过为了避免有太多的回调链,我会把它包在一个承诺中(当然这也需要一些适当的错误处理)。
//@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)
}