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

Express JS API返回Undefined,前端Fetch获取值异常求助

问题分析与解决:Express API返回值在前端fetch后显示undefined

核心问题很明确:后端API返回的字段是url,但前端代码里尝试解构的是image字段,字段名称不匹配,所以image变量自然会是undefined。

修复方案二选一即可:

方案1:修改前端代码,匹配后端返回的字段

把前端里的解构字段从image改成url,后续使用url变量:

const response = await fetch('http://localhost:8080/', {
  method: 'GET',
});

const { url } = await response.json(); // 改为匹配后端的url字段

console.log(url)

const result = document.querySelector('#result');
result.innerHTML = `<img src="${url}" width="512" />`; // 同步替换为url变量

方案2:修改后端代码,返回前端期望的字段

把后端返回的对象字段从url改成image:

import express from 'express';
import cors from 'cors';

const app = express();
app.use(cors());
app.use(express.json());
app.use((req, _, next) => {
    console.log(req);
    next();
});

app.get('/', async (_, res) => {
    // 改为返回前端期望的image字段
    res.send({ image:'https://gifdb.com/images/high/you-got-rick-rolled-rick-astley-dance-2s99zcvywfvs3kao.gif' });
});

app.listen(8080, () => console.log('http://localhost:8080/'));

额外提示:排查这类问题时,可以先在浏览器直接访问http://localhost:8080/,查看返回的JSON结构,确认字段名是否和前端代码匹配,这是快速定位问题的有效方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 19:43:25