我最近遵循了關於如何構建快速服務器(https://codeforgeek.com/2014/06/express-nodejs-tutorial/)的簡單教程。快速服務器 - 無法開機自檢/
我想擴展本教程中的代碼,以便我可以回覆發佈請求。我想通過更新JSON文件來做到這一點(恰好是充滿了「用戶評論」,然後在「/」
./server.js重新描繪:
var express = require('express');
var app = express();
// routing configuration
require('./router/main')(app);
// ejs configuration
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
// run the server
var server = app.listen(8080, function(){
console.log('Express server listening on port 8080');
});
。 /router/main.js(路由器):
var fs = require('fs');
var ejs = require('ejs')
module.exports = function(app){
app.get('/', function(req, res){
var comments = JSON.parse(fs.readFileSync(__dirname + '/../comments.json'));
res.render('index.ejs', comments);
});
app.post('/', function(req, res){
console.log('here in post');
var name = req.body.name;
var message = req.body.message;
var newComment = {"name": name, "message": message};
var comments = JSON.parse(fs.readFileSync(__dirname + '/../comments.json'));
comments.push(newComment);
fs.writeFileSync(__dirname + '/../comments.json', comments, 'utf8');
//redirect to a 'get' on '/'
res.redirect('/');
});
app.get('/about', function(req, res){
res.render('about.html')
});
}
./views/index.ejs:
<div>
<div>
<h1> Joe's Forum </h1>
<a href='/about'> (about) </a>
</div>
<div>
<ul>
<% comments.forEach(function(comment){ %>
<li>
<%= comment.name %> : <%= comment.message %>
</li>
<% }); %>
</ul>
</div>
<h2> Enter a new comment </h2>
<form action='/' method="post">
Enter your name: <input type='text' name='name'> <br><br>
Enter your message: <input type='textarea' name='message'> <br><br>
<input type='submit' value='Submit'>
<form>
</div>
./comments.json:
{
"comments": [
{"name":"Joe", "message" : "What advantages does Node.js afford the web developer?"},
{"name": "John", "message": "Asynchronous IO helps us to keep our pages responsive even if the server is fetching data"}
]
}
當我試圖從我的形式提交新的評論,我看到的是這樣的:
「不能發佈/」
有人可以解釋爲什麼我可能會得到這個錯誤嗎?謝謝
你正在做的真正禁忌的東西。你永遠不應該使用nodeJS的'Sync' api,當然不能使用express服務器的響應。也沒有錯誤檢查任何地方,所以你的服務器將非常容易崩潰。你能顯示「comments.json」的內容嗎? – caasjj
好吧。然而,我只是想「讓它成爲工作」,以此作爲學習Express的練習。我知道這不是很棒的代碼。一旦我收到「發佈請求」,我打算將其清理乾淨(即訂閱最佳做法)。按照要求,我會編輯包含comments.json。 –
完全不是意味着批評 - 只是指出你可能會或可能沒有意識到的東西。現在,我想我也明白爲什麼你的代碼行爲不當。你正在'Object'上做'comments.push',而不是'Array'。讓我看看我能否爲你解決一個明確的答案。 – caasjj