Node.js+EJS下myblog向backend传递posts数据的问题排查
问题:如何从接口获取posts数据而非渲染后的EJS页面?
现有代码
main.js
let posts = [ { title: "Hello World!", content: "Hello World!", date: "01klfljs", } ]; app.use(bodyParser.urlencoded({extended: true})); app.use(express.static("public")); app.use(bodyParser.json()); app.get("/", (req,res) => { res.render("index.ejs"); }); app.get("/myblog", (req,res) => { res.render("myblog.ejs", { posts }); }); app.post("/myblog", (req,res) => { const post = { title: req.body.title, content: req.body.content, date: new Date(), } posts.push(post); });
待整合的myblog.js
const api_url = "http://localhost:3000"; app.use(express.static("public")); app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser.json()); app.get("/", async(req,res) => { try{ const {posts} = req.body; const response = await axios.get(`${api_url}/myblog`); res.render("backend.ejs",{ posts: response.data, }); } catch(error){ res.status(500); } });
backend.ejs
<body> <a href="/new">Create a New Post</a> <div> <ul> <% post.forEach(post => {%> <li> <h2><%= post.title %></h2> <h3><%= post.content %></h3> <h4><%= post.date %>/h4> </li> <% }); %> </ul> </div>
myblog.ejs
<body> <ul> <% posts.forEach(post => { %> <li> <h2><%= post.title %></h2> <h3><%= post.content %></h3> <h4><%= post.date %></h4> </li> <% }); %> </ul> </body>
当前通过axios请求/myblog接口时,返回的是渲染后的myblog.ejs页面,而非纯posts数据,需要修改实现仅传递posts数据到backend.ejs渲染。
解决方法
核心问题是/myblog接口当前直接渲染EJS页面,没有提供纯数据的API接口,按以下步骤修改:
- 新增返回JSON数据的API接口
在main.js中添加专门返回posts数据的接口:
// 在main.js中新增该接口 app.get("/api/posts", (req, res) => { res.json(posts); // 直接返回posts数组的JSON格式 });
- 修改请求地址为新API
调整myblog.js中的请求目标,从/myblog改为新增的/api/posts:
// 修改myblog.js中的请求部分 const response = await axios.get(`${api_url}/api/posts`);
- 修复backend.ejs的语法错误
循环变量名写错,且标签闭合错误,修正后:
<ul> <% posts.forEach(post => {%> <li> <h2><%= post.title %></h2> <h3><%= post.content %></h3> <h4><%= post.date %></h4> </li> <% }); %> </ul>
- 整合myblog.js到main.js的注意事项
- 去掉重复的中间件注册(
app.use(express.static)等在main.js已存在) - 确保安装并引入axios:
const axios = require('axios'); - 修改myblog.js的路由,避免和main.js根路由冲突,比如改成
/backend:
// 整合后的main.js新增backend路由 app.get("/backend", async(req,res) => { try{ const response = await axios.get(`${api_url}/api/posts`); res.render("backend.ejs",{ posts: response.data, }); } catch(error){ console.error(error); res.status(500).send("服务器错误"); } });
内容的提问来源于stack exchange,提问作者Mr. Nobody
相关产品推荐
相关产品推荐

