如何在Express.js的GET接口中返回epicgames-status API的回调输出
代码修复说明
原代码存在的问题
- 作用域错误:在
EpicGamesAPI().then()回调内部用const声明的epicgames属于块级作用域变量,外部路由函数无法访问 - 赋值错误:
const epicgames = console.log(callback)写法无效,console.log()返回值为undefined,并未存储接口返回的实际内容 - 执行逻辑错误:异步接口请求写在路由外部,仅服务启动时执行一次,无法获取最新状态,且请求未完成时访问接口会返回异常
推荐修复方案(每次请求获取最新状态)
该方案每次收到用户请求时都会调用Epic Games接口获取最新状态,适用性更强:
const EpicGamesAPI = require('epicgames-status'); const express = require('express') const app = express() const port = 3000 app.get('/', async (req, res) => { try { // 等待Epic Games接口返回结果 const epicgames = await EpicGamesAPI() // 返回接口数据给请求方 res.send(epicgames) } catch (error) { // 接口请求失败时返回错误提示 res.status(500).send('获取Epic Games状态失败:' + error.message) } }) app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`) })
可选方案(服务启动时仅请求一次缓存数据)
如果不需要实时更新状态,可以选择该方案,仅在服务启动时拉取一次数据缓存使用:
const EpicGamesAPI = require('epicgames-status'); const express = require('express') const app = express() const port = 3000 // 全局变量缓存接口数据 let epicgamesCache = null // 服务启动时拉取一次接口数据 EpicGamesAPI() .then(data => epicgamesCache = data) .catch(err => console.error('初始化拉取Epic Games状态失败:', err)) app.get('/', (req, res) => { if (epicgamesCache) { res.send(epicgamesCache) } else { res.status(503).send('服务初始化中,请稍后重试') } }) app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`) })
内容的提问来源于stack exchange,提问作者Lucas
相关产品推荐
相关产品推荐

