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

Canvas单词显示功能异常:fetch请求404错误排查求助

Canvas随机单词显示功能故障修复

问题现象

Canvas随机单词显示功能未按预期工作,客户端launchWord函数存在问题:本该显示随机单词的位置显示错误代码,控制台输出404请求失败信息。

客户端代码

function launchWord() {
    fetch('/word')
        .then(response => response.text())
        .then(word => {
            const x = Math.random() * (canvas.width - 100);
            const y = Math.random() * (canvas.height - 30);
            const direction = getRandomDirection();
            const bgColor = getRandomColor();
            const textColor = getContrastingColor(bgColor);

            const bouncingWord = new BouncingWord(word, x, y, direction.dx, direction.dy, bgColor, textColor);
            words.push(bouncingWord);
        });
}

服务端对应接口代码

app.get('/word', (req, res) => {
    const word = words[Math.floor(Math.random() * words.length)];
    res.json({ word });
});

app.listen(PORT, () => console.log(`Server running at http://localhost:${PORT}`));

错误信息

script.js:77 
 GET http://127.0.0.1:5501/word 404 (Not Found)
launchWord  @   script.js:77
(anonymous) @   script.js:105

故障原因与修复方案

核心问题

  1. 请求地址不匹配:客户端通过静态服务器(端口5501)运行,而服务端在独立端口启动,直接用相对路径/word会请求静态服务器而非后端服务,导致404。
  2. 响应解析方式错误:服务端返回JSON格式数据{ word: "xxx" },但客户端用response.text()解析,会把JSON字符串直接当作单词显示,最终出现错误代码。

修复步骤

  1. 修正请求地址:将fetch的目标地址改为服务端的完整URL(替换成你的服务端实际端口,比如3000);
  2. 修正响应解析逻辑:改用response.json()解析JSON数据,并取出其中的word字段;
  3. 添加错误处理:捕获请求失败的情况,避免功能完全崩溃。

修复后的客户端代码

function launchWord() {
    // 替换为你的服务端实际端口
    fetch('http://localhost:3000/word')
        .then(response => {
            if (!response.ok) {
                throw new Error(`请求失败:${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            const word = data.word;
            const x = Math.random() * (canvas.width - 100);
            const y = Math.random() * (canvas.height - 30);
            const direction = getRandomDirection();
            const bgColor = getRandomColor();
            const textColor = getContrastingColor(bgColor);

            const bouncingWord = new BouncingWord(word, x, y, direction.dx, direction.dy, bgColor, textColor);
            words.push(bouncingWord);
        })
        .catch(error => {
            console.error('获取随机单词失败:', error);
        });
}

服务端优化建议

为避免服务端words数组为空导致返回undefined,可添加边界判断:

app.get('/word', (req, res) => {
    if (words.length === 0) {
        return res.status(400).json({ error: '无可用单词' });
    }
    const word = words[Math.floor(Math.random() * words.length)];
    res.json({ word });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 19:37:49