【发布时间】:2020-12-10 08:24:34
【问题描述】:
我有这个 JSON 文件,我将其用作名为 data.json 的数据库。
{
"car": {
"quantity": 2,
"price": 100
}
我在 node.js 上有这个代码叫做 app.js
var data = fs.readFileSync("data.json");
var jData = JSON.parse(data);
// console.log(jData);
////////ROUTES///////////
app.get("/", home);
// New item create path
app.get("/new/:id/:quantity/:price?", newItem);
function newItem(req, res){
var itemData = req.params;
////// shows :id as name
var newName = itemData.id;
////// shows :price as price
var newPrice = Number(itemData.price);
var newQuantity = Number(itemData.quantity);
var reply;
//// Object created
function ItemObj(quantity, price) {
this.quantity = quantity;
this.price = price;
}
///// Assing attributes to object
var createItem = new ItemObj(newQuantity, newPrice);
// print stuff
res.send("This new " + newName + " has been added! and it costs " +
newPrice);
////// If prices is not set
if(!newPrice){
reply = ("price is required")
//////////then---->
} else {
jData[newName] = createItem;
var stringData = JSON.stringify(jData, null, 2);
fs.writeFile("data.json", stringData, finished);
function finished(err, info){
console.log("updated");
}
res.render("index", {jData: jData})
}
然后我有一个名为 index.ejs 的 EJS 代码,当我尝试将 JSON 数据库 (jData) 传递给 EJS 以显示它们的值时,我收到一条错误消息“未定义 jData”
<h1>Hello bro</h1>
<%= JSON.stringify(jData) %>
我在哪里犯了错误,如何让 json 文件显示在 index.ejs 文件上?谢谢!
【问题讨论】:
标签: javascript node.js json api ejs