新增功能:更具體的描述Node.js:如何在按下提交按鈕時將公式的輸入值寫入JSON文件?
我正在編程一個網站,使用不同類型的不同產品。每個產品都有一個帶有評論功能的詳細頁面。產品詳情網站的路徑看起來像http://localhost:3000/details/type/name。當用戶填寫表單以撰寫評論並按下提交按鈕,所有的數據應被追加到產品類型的JSON文件,該文件是這樣的:
type1.json
[
{
"name": "Product1",
"description": "Description1",
"comments":[
{
"user": "Matthew",
"message": "Very Good!",
"timestamp": "2017-03-17T17:51Z"
},{
"user": "Lea",
"message": "Nice",
"timestamp": "2017-03-10T13:29Z"
}
]
},
{
"name": "Product2",
"description": "Description2",
"comments":[
{
"user": "Ann",
"message": "This is very useful!",
"timestamp": "2017-02-02T19:30Z"
},{
"user": "Tim",
"message": "Awesome",
"timestamp": "2017-04-01T20:25Z"
}
]
]
這是我的HTML文件的一部分,其中包含的形式:
details.html
<form action="" method="POST" id="commentForm">
<div class="form-group">
<input type="text" id="name"
placeholder="Name" class="form-control" name="name"/>
</div>
<div class="form-group">
<textarea cols="30" rows="5" class="form-control" id="message" placeholder="Message" name="message"></textarea>
</div>
<div class="form-group">
<div class="col-md-6 text-center">
<button type="reset" class="btn btn-default">
<span class="glyphicon glyphicon-remove"></span>
Reset
</button>
</div>
<div class="col-md-6 text-center">
<button type="submit" class="btn btn-success">
<span class="glyphicon glyphicon-ok"></span>
Send
</button>
</div>
</div>
</form>
這是我的JavaScript文件的相關部分:
details.js
$(function() {
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$("#commentForm").bind("submit", function(evt) {
console.log(JSON.stringify($("#commentForm").serializeObject()));
$.ajax({
url: window.location.pathname,
type: "POST",
contentType: "application/json",
data: JSON.stringify($("#commentForm").serializeObject()),
success: function(data) {
console.log('success');
console.log(JSON.stringify(data));
},
});
return false;
});
});
現在的問題是:什麼在app.js寫? 以下是當前app.js的摘錄。
app.js
const express = require("express");
const app = express();
const fs = require('fs');
const path = require("path");
const jsonfile = require('jsonfile');
const bodyParser = require('body-parser');
app.use(bodyParser.json());
const type1File = __dirname + "/data/type1.json";
...
app.post("/details/:typ/:name", function (req, res) {
if (req.params.typ == "type1") {
const apps = readJsonFile(type1File);
res.send(getProduct(apps, req));
???What to write here???
}
...
});
function readJsonFile(file) {
try {
const data = fs.readFileSync(file);
return JSON.parse(data);
} catch (e) {
console.log(file + "could not be read. " + e);
return [];
}
}
我應該怎麼加?數據如何被寫入正確的JSON對象的「註釋」鍵?請幫助我,我花了很多時間嘗試不同的事情,但沒有什麼是正確的。
感謝您的回答!我應該如何寫出表單數據將寫入JSON文件中正確的「註釋」鍵? – LCP