【问题标题】:How do I properly route data through my Node API?如何通过我的 Node API 正确路由数据?
【发布时间】: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


    【解决方案1】:
    1. 请学习 promise 和 await 语法。生活会更轻松。
    2. 切勿抛出字符串。总是喜欢一个真正的错误对象,比如: throw new Error('xxx');这样你总是会得到一个堆栈。它更易于调试。
    3. 避免回调地狱:http://callbackhell.com/
    4. 您需要决定是否要在控制器或服务中捕获错误。两者都不需要。
    5. 在控制器中以这种方式调用服务:
    ordersCountService((error, data) => {
    

    但你这样声明:

    const ordersCountService = (req, res) => {
    

    这是不兼容的。如果您使用回调样式,它应该看起来像这样:

    const ordersCountService = (callback) => {
    ...
    if (error) return callback(error)
    ...
    callback(null, gooddata);
    

    这是一个将您的 ordersCountService 函数展平为等待语法的示例,它允许您尝试执行“返回数据”:

    const fetch = require('node-fetch');
    
    // connect to api and make initial call
    const ordersCountService = async (req, res) => {
        const url = ...;
    
        const settings = { method: 'Get'};
        try {
            const res = await fetch(url, settings);
            if (!res.ok) throw new Error('Unable to retrieve data');
    
            return await res.json();
        } catch(error) {
            console.log(error);
        }
    }
    
    module.exports = ordersCountService;
    

    事实上,我更愿意在控制器中处理错误。那么这作为一项服务就足够了

    const fetch = require('node-fetch');
    
    // connect to api and make initial call
    const ordersCountService = async () => {
        const url = ...;
    
        const settings = { method: 'Get'};
        const res = await fetch(url, settings);
        if (!res.ok) throw new Error('Unable to retrieve data');
    
        return await res.json();
    }
    
    module.exports = ordersCountService;
    

    然后你可以这样调用这个函数:

    try {
      const data = await ordersCountService(req, res);
    } catch(err) {
      console.log(err);
    }
    
    //or 
    ordersCountService(req, res).then((data) => console.log(data)).catch((err) => console.error(err));
    

    【讨论】:

      猜你喜欢
      • 2019-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-07
      • 2017-11-23
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多