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

Fetch请求Koa后端GET接口后无法获取返回结果的问题求助

问题:Fetch请求后端正常响应但前端无输出?

我正在编写一个通过Fetch向Koa后端发送GET请求并获取结果的程序。后端功能正常,点击提交按钮时后端控制台能正确打印结果,但前端控制台无任何输出,尝试使用alert(res)也无效。

后端代码:

const koa = require('koa');
const router = require('koa-router');
const cors = require('koa2-cors');
const app = new koa();
app.use(cors());
const _ = router();
const port = 3000;

_.get('/', async (ctx) => {
    const result = "good morning";
    console.log(result);
    ctx.body = result;
});

app.use(_.routes());

app.listen(port, () => {
    console.log(`Server listening on port`);
});

前端代码:

submitButton.addEventListener('click', async () => {
    fetch(`http://localhost:3000/`)
        .then(res => console.log(res));
});

问题原因与解决方案

核心问题

Fetch API的使用存在两个关键疏漏:

  1. 未解析响应体:你直接打印的res是Fetch返回的Response对象,并非后端返回的实际数据,必须调用解析方法才能获取响应内容。
  2. 未处理异常:缺少异常捕获逻辑,若请求过程中出现错误(比如网络波动、潜在的跨域问题),错误会被静默忽略,无法在控制台看到提示。

修正后的前端代码

基于Promise链式调用的写法

submitButton.addEventListener('click', () => {
    fetch(`http://localhost:3000/`)
        // 先验证响应状态是否正常
        .then(res => {
            if (!res.ok) {
                throw new Error(`请求失败,状态码:${res.status}`);
            }
            return res.text(); // 解析文本类型的响应体(你的后端返回的是纯文本)
        })
        // 处理解析后的实际数据
        .then(data => {
            console.log(data); // 此时会打印"good morning"
            alert(data);
        })
        // 捕获并打印所有异常
        .catch(err => {
            console.error('请求出错:', err);
        });
});

基于async/await的写法(更简洁)

因为你的事件回调已经标记为async,可以用这种写法:

submitButton.addEventListener('click', async () => {
    try {
        const res = await fetch(`http://localhost:3000/`);
        if (!res.ok) {
            throw new Error(`请求失败,状态码:${res.status}`);
        }
        const data = await res.text();
        console.log(data);
        alert(data);
    } catch (err) {
        console.error('请求出错:', err);
    }
});

额外优化建议

后端的listen回调可以补充端口号打印,方便确认服务运行状态:

app.listen(port, () => {
    console.log(`Server listening on port ${port}`);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 02:35:31