You need to enable JavaScript to run this app. 如何正确在Node API中路由传递数据并返回接口响应?
优惠活动
大模型
产品
解决方案
定价
更多

如何正确在Node API中路由传递数据并返回接口响应?

问题排查与修复方案

核心错误点

  • 文件名引入不匹配:控制器中引入的路径是../services/ordersCountService,但你的服务层文件实际命名为ordersService.js,找不到对应模块,首先需要统一文件名:要么将服务层文件名改为ordersCountService.js,要么修改控制器中的引入路径为require('../services/ordersService')。
  • 服务层入参不匹配:控制器调用ordersCountService时传入的是回调函数,但当前服务层定义的入参是(req, res),没有接收回调函数,导致回调永远不会执行,接口无响应。
  • 异步逻辑未正确传递结果:fetch是异步操作,当前服务层中既没有将请求结果/错误传递给回调,也没有返回异步结果,控制器永远拿不到返回数据。
  • fetch链式调用缺少返回:res.json()是异步操作,你没有将它return到外层链式调用,导致后续无法拿到解析后的JSON数据。

修复代码

方案1:兼容原有回调写法

services/ordersCountService.js(文件名已统一)

const fetch = require('node-fetch');

// 入参改为接收回调函数
const ordersCountService = (callback) => {
    const url = '替换为你实际的第三方API地址';
    const settings = { method: 'GET'};

    fetch(url, settings)
        .then(res => {
            if (res.ok) {
                // 返回res.json()的Promise到外层
                return res.json();
            } else {
                throw new Error('Unable to retrieve data');
            }
        })
        .then(data => {
            // 调用回调传递数据
            callback(null, data);
        })
        .catch(error => {
            console.log(error);
            // 调用回调传递错误
            callback(error, null);
        });
}

module.exports = ordersCountService;

控制器代码无需修改即可正常运行。


方案2:更简洁的async/await写法(推荐,避免回调地狱)

services/ordersCountService.js(文件名已统一)

const fetch = require('node-fetch');

const ordersCountService = async () => {
    const url = '替换为你实际的第三方API地址';
    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;

controllers/ordersCountController.js

const ordersCountService = require('../services/ordersCountService');

const ordersCountController = async (req, res) => {
    try {
        const data = await ordersCountService();
        res.send({ data });
    } catch (error) {
        res.send({ error: error.message });
    }
};

module.exports = ordersCountController;

额外注意

如果运行时报require() of ES Module xxx错误,说明你安装的是node-fetch v3版本,该版本仅支持ESM导入语法,执行npm install node-fetch@2安装v2版本即可正常使用require引入。

内容的提问来源于stack exchange,提问作者DougM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 03:24:07