You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过模块导出API响应至其他JS文件?遇404报错求解决

解决JS模块导入404错误及异步数据计算问题

一、修复404 Not Found错误

出现该错误是因为浏览器无法定位到你要导入的文件,按以下步骤排查解决:

  • 补充文件后缀:在ES模块导入时,部分本地服务器(如Live Server)要求明确指定.js后缀,修改导入代码:
    import { estimatedReadingTime } from "./api_responses.js"
    
  • 核对路径与文件名:确认api_responses.js文件确实在当前导入文件所在的js目录下,检查文件名的拼写、大小写完全匹配(比如不要写成api_Response.js这类变体)。

二、修复代码逻辑错误

即便路径问题解决,原代码仍会触发Cannot read properties of undefined (reading 'articles')错误,核心问题是异步数据处理逻辑混乱,修改后的完整代码如下:

调整后的api_responses.js

// 假设API_KEY已在当前作用域定义
async function getData() {
    try {
        const response = await fetch(`https://newsapi.org/v2/top-headlines?country=in&apiKey=${API_KEY.appID}`)
        return await response.json()
    } catch (err) {
        console.error('获取新闻数据失败:', err)
        return null
    }
}

// 增加参数校验,避免数据异常导致报错
const calculateReadTime = (content) => {
    if (!content) return 0
    const plusIndex = content.indexOf('+')
    if (plusIndex === -1) return 0
    const spaceIndex = content.indexOf(' ', plusIndex + 1)
    const charCount = parseInt(content.slice(plusIndex + 1, spaceIndex), 10)
    if (isNaN(charCount)) return 0
    return Math.ceil(((charCount + 100) / 4) / 200)
}

// 导出异步函数,确保先获取数据再计算阅读时间
export async function getEstimatedReadingTime() {
    const newsData = await getData()
    if (!newsData?.articles?.[0]?.content) return 0
    return calculateReadTime(newsData.articles[0].content)
}

调整后的导入文件代码

import { getEstimatedReadingTime } from "./api_responses.js"

// 处理异步返回的结果
getEstimatedReadingTime().then(readingTime => {
    console.log('预估阅读时间:', readingTime)
}).catch(err => {
    console.error('计算阅读时间失败:', err)
})

修改说明

  1. 移除全局response变量,改用局部变量避免作用域污染;
  2. 给阅读时间计算函数增加参数校验,防止API返回数据格式异常时崩溃;
  3. 不再同步导出计算结果,而是导出异步函数,保证先完成API请求再执行计算;
  4. 导入文件通过.then()处理异步结果,符合JS异步代码执行逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 12:15:43