我有一个简单的服务器,并且可以完美地通过浏览器获取url上的数据。我正在尝试在我的ejs模板中获取数据。
这是我获取数据的方式:
app.get('/some', function(req, res, next) {
var size = 3;
var curr = req.query.page || 1;
var allSome = Object.assign([], jsFile.some);
some = allSome.slice((curr - 1) * size, curr * size);
some = some.map(function(som) {
var mapSome = Object.assign({}, som);
delete mapSome.var1;
delete mapSome.var2;
return mapSome;
});
return res.json({
some: some,
total: allSome.length,
});
});
这就是我试图传递数据的方式:
app.get('/some', function (req, res, next) {
res.render('events', {data : res.json.some});
});
这就是我试图获取数据的方式:
<ul>
<% data.forEach(function(dat) { %>
<li><%= dat.var3 %></li>
<li><%= dat.var4%>
<% }); %>
</ul>
但是我得到了:
无法读取未定义的属性“ forEach”
我是ejs和前端的新手。如果有人可以帮助我,我将不胜感激。
答案 0 :(得分:1)
此代码块将以json
进行响应,而不会传递给下一个middleware
return res.json({
some: some,
total: allSome.length,
});
用以下内容替换上面的块:
res.render('events', {data : some});
答案 1 :(得分:0)
index.js
文件:let express = require("express");
let app = express();
app.set("viwe engine", "ejs");
app.listen(80, () => {
console.log("iam ok! *:80")
});
app.get("/", (req, res) => {
res.render("index.ejs", {
data: {
data: {
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}
}
})
})
index.ejs
文件:<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>HI</h1>
<input id="EJSData" value="<%= JSON.stringify(data) %>"/>
<script id="EJSDataLoader">
(()=>{
let ejsDataElm = document.getElementById("EJSData");
let scElm = document.createElement("script");
scElm.innerHTML = `const EJSData = ()=>{return ${ejsDataElm.value}}`;
document.body.appendChild(scElm);
document.body.removeChild(document.getElementById("EJSData"));
document.body.removeChild(document.getElementById("EJSDataLoader"));
})();
</script>
</body>
</html>
答案 2 :(得分:0)
您没有写li关闭标签
<base href="/app1/"/>