React无法获取接口返回的currentLoggedInUserId字段求助
问题分析与解决方案
嘿,我帮你梳理下问题根源和修复步骤,很快就能搞定:
1. 核心问题:请求路径不匹配
你的后端接口明确定义的路径是:
server.get("/api/decision/decisionCode/:decisionCode", ...)
但React端axios请求的路径却是:
axios.get(`${ROOT_URL}/api/decision/${decisionCode}`, { headers })
注意看,后端路径里有/decisionCode/这个中间段,但React请求直接跳过了它!这导致你React请求的根本不是你写的那个带currentLoggedInUserId的接口,大概率是请求到了另一个直接返回Decision数组的接口,所以res.data里自然没有额外字段。
2. 次要问题:数据包装与解析逻辑不匹配
后端你用Object.assign({decision}, {currentLoggedInUserId})返回的是一个包含数组和用户ID的对象(结构是{ decision: [...], currentLoggedInUserId: "xxx" }),但React端却在尝试从res.data[0]里取currentLoggedInUserId,这明显是解析逻辑错了——用户ID不在数组元素里,而是和数组同级的顶层字段。
修复步骤
第一步:修正React端的请求路径
把axios请求改成和后端完全匹配的路径:
axios.get(`${ROOT_URL}/api/decision/decisionCode/${decisionCode}`, { headers })
第二步:调整React端的响应解析逻辑
因为后端返回的是包装后的对象,所以要调整取值方式:
.then(res => { // 先从返回对象里拿到决策数组的第一个元素 const targetDecision = res.data.decision[0]; console.log('决策创建者ID:', targetDecision.decisionCreatorId); console.log('当前登录用户ID:', res.data.currentLoggedInUserId); // 直接从顶层取 this.setState({ decision: targetDecision.decisionText, answersArray: targetDecision.answers.map(x => x.answerText), decisionCreatorId: targetDecision.decisionCreatorId, currentLoggedInUserId: res.data.currentLoggedInUserId, // 正确的取值位置 voteOver: targetDecision.voteOver }); })
可选优化:后端用findOne替代find(更合理的查询)
如果decisionCode是唯一标识,用findOne替代find会更高效,返回单个对象而非数组,后端代码可以简化成:
Decision.findOne({ decisionCode: decisionCode }).then(decision => { if (!decision) { return res.status(STATUS_NOT_FOUND).json({ error: "Decision with code " + decisionCode + " not found" }); } // 把用户ID直接合并到决策对象里返回 return res.status(STATUS_OKAY).json({ ...decision.toObject(), currentLoggedInUserId }); })
对应的React端解析也更简单,不需要再从res.data.decision里取数组元素,直接用res.data的字段即可。
这样调整后,你就能在React端正常拿到currentLoggedInUserId字段了。
内容的提问来源于stack exchange,提问作者padjo
相关产品推荐
相关产品推荐

