通过fetch从Express服务端取数,前端无法正常展示获取的字符串
前后端数据展示问题排查与修复
代码中存在的具体问题
- 模块引入路径错误:路由文件中写的
require("pathJs")不符合CommonJS规范,本地自定义模块必须写相对路径(比如./pathJs),否则服务启动时就会直接报错找不到模块,无法正常运行。 - 路由路径匹配失效:主入口将路由统一挂载在
/api前缀下,但路由文件里的路由写法没有加前导斜杠(PathRoute),会导致路径拼接错误,和前端请求的/api/PATH完全无法匹配,请求直接命中404。 - 日志判断误导:工具模块文件末尾直接调用了
callName(),这段代码会在模块被引入加载到Express服务时立刻执行,你看到的服务端console.log是模块加载阶段的输出,根本不是前端发请求触发接口执行的结果,导致你误以为接口逻辑已经跑通。 - 返回值结构不匹配:后端
callName()最终返回的是纯字符串"this works",res.json()序列化后,前端拿到的响应体就是这个字符串本身,不存在liner这个对象字段,所以前端写response.liner永远取到undefined,自然无法渲染。 - 冗余无效逻辑:
name()是普通同步函数,没有返回Promise,对它加await没有任何实际作用;前端用setTimeout包裹res.json()的写法也完全无意义。 - 前端执行逻辑缺失:
- 定义了
caller()请求函数,但页面加载完成后从来没有主动调用它,实际根本不会发出接口请求。 - 页面里的p标签设置了
color: white,如果页面背景为白色,就算字符串渲染出来也会因为和背景同色完全看不见。
- 定义了
修复后的完整代码
1. 工具模块(pathJs.js)
function name() { const liner = "this works" console.log(liner) return liner; } async function callName() { const data1 = name() // 包装为对象结构,匹配前端取字段的逻辑 return { liner: data1 }; } // 去掉模块加载时自动执行的调用,避免日志误导 module.exports = { callName }
2. 路由文件(routePath.js)
const router = require("express").Router(); // 修正为相对路径引入 const { callName } = require("./pathJs"); // 修正路由路径,加前导斜杠,和前端请求地址保持一致 router.route("/PATH").get(async(req, res) => { const Result = await callName(); return res.json(Result); }); module.exports = router;
3. 服务主入口文件
const express = require("express"); const cors = require("cors"); const routePath = require("./routePath"); require("dotenv").config({ debug: process.env.DEBUG }); const port = process.env.PORT || 5000; const app = express(); app.use(cors()); app.use(express.json()); app.use("/api", routePath); app.listen(port, () => { console.log(`server is running on port: http://localhost:${port}`); });
4. 前端页面代码
<!-- 调整字色为黑色,避免白字白底不可见 --> <p id="insertHere" style="color: black;"></p> <script> async function caller() { // 去掉无意义的setTimeout包裹,简化请求处理逻辑 const res = await fetch(`http://localhost:5000/api/PATH`); const response = await res.json(); console.log(response) document.getElementById("insertHere").innerHTML = response.liner } // 页面加载完成后主动触发请求,否则函数定义了不会执行 window.onload = caller; </script>
内容的提问来源于stack exchange,提问作者anon20010813
相关产品推荐
相关产品推荐

