【发布时间】:2021-09-08 09:44:38
【问题描述】:
我有以下文件:
我的路线 - orders_count 路线所在的位置:
routes/index.js
const express = require('express');
const router = express.Router();
const transactionsController = require('../controllers/transactionsController');
const ordersController = require('../controllers/ordersController');
const ordersCountController = require('../controllers/ordersCountController');
router.get('/transactions', transactionsController);
router.get('/orders', ordersController);
router.get('/orders_count', ordersCountController);
module.exports = router;
然后我将订单计数控制器放在控制器目录中:
controllers/ordersCountController.js
const ordersCountService = require('../services/ordersCountService');
const ordersCountController = (req, res) => {
ordersCountService((error, data) => {
if (error) {
return res.send({ error });
}
res.send({ data })
});
};
module.exports = ordersCountController;
然后我的控制器调用我的订单计数服务,该服务从另一个 API 获取数据。
services/ordersService.js
const fetch = require('node-fetch');
// connect to api and make initial call
const ordersCountService = (req, res) => {
const url = ...;
const settings = { method: 'Get'};
fetch(url, settings)
.then(res => {
if (res.ok) {
res.json().then((data) => {
return data;
});
} else {
throw 'Unable to retrieve data';
}
}).catch(error => {
console.log(error);
});
}
module.exports = ordersCountService;
我正在尝试返回 JSON 响应。我最初用请求设置它,但查看 NPM 站点,它似乎已经贬值,所以一直在研究如何使用 node-fetch。
'return data' 和 res.send({data}) 我都试过了,但都没有解决问题。
我还是新手,所以我可能遗漏了一些非常明显的东西,但我为什么不将 JSON 发回以使其显示在 /api/orders_count 端点?
我一直认为我在控制器中搞砸了一些东西,但我看了这么久,似乎无法弄清楚。
任何帮助都将不胜感激,如果有什么我可以添加以清楚起见,请不要犹豫。
最好的。
【问题讨论】:
标签: javascript node.js api node-fetch