一個簡單的TodoList
image.png
- 在將待辦事項添加到數組中之前,你需要得到完整的字符串。要得到整個字符串,可以將所有數據塊拼接到一起,直到表明請求已經完成的end事件被發射出來。在end事件出來后,可以用請求體的整塊內容組裝出item字符串,然后壓入items數組中。在添加好事項后,你可以用字符串OK和Node的默認狀態碼200結束響應
執行文件index.js
'use strict';
let http = require('http');
let todo = require('./todoModule');
// 用一個常規的JavaScript數組存放數據
let items = [];
let server=http.createServer((req,res)=>{
if('/'==req.url){
console.log(req.method);
switch(req.method){
case 'GET':
todo.show(res,items);
break;
case 'POST':
todo.add(req, res,items);
break;
default:
todo.badRequest(res);
}
}
else{
todo.notFound(res);
}
})
server.listen(32001);
依賴模塊 todoMoudle.js
'use strict';
let qs = require('querystring');
function show(res, items) {
console.log(items);
let html = `
<html>
<head>
<title>
TodoList
</title>
</head>
<body>
<h1>
Todo List
</h1>
<ul>
${items.map(item => `
<li>${item}</li>`
).join('')}
</ul>
<form action="/" method="post">
<p><input type="text" name="item"></p>
<p><input type="submit" value="Add Item"></p>
</form>
</body>
</html>
`
res.setHeader('Content-type', 'text/html');
res.setHeader('Content-Length', Buffer.byteLength(html));
res.end(html);
};
function add(req, res, items) {
//為進來的事項設置字符串緩存
let body = '';
req.setEncoding('utf8');
req.on('data', (chunk) => {
body += chunk;
})
req.on('end', () => {
let obj = qs.parse(body);
items.push(obj.item);
show(res, items);
})
}
//notFound()函數接收響應對象,將狀態碼設為404,響應主體設為Not Found:
function notFound(res) {
res.statusCode = 404;
res.setHeader('Content-type', 'text/plain');
res.end('Not Found');
};
//返回400 Bad Request響應的函數實現起來跟notFound()幾乎一樣,向客戶端指明該請求無效:
function badrequest(res) {
res.statusCode = 400;
res.setHeader('Content-type', 'text/plain');
res.end('badrequest');
};
module.exports = {show, add, notFound, badrequest}