NodeJs实战-待办列表-增删改查
- 项目结构
- 增加表单提交事件
- 修改 index.html
- NodeJS 服务端增删改查
- 修改 server.js
- 效果图
- 初始页面
- 输入 1111,点击添加
- 输入 1111 点击完成
项目结构
增加表单提交事件
修改 index.html
- 引入 jquery
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
- 增加添加、完成按钮事件
<script type="text/javascript">
$(function() {
$("#add").on('click', function(){
add();
});
$("#complete").on('click', function(){
complete();
});
});
function add() {
var item = $("#item_text").val().trim();
if (item.length == 0) {
alert('输入数据不能为空');
}
$.ajax({
url: "/add",
method: 'GET',
data: {
item: item
},
success: function(result) {
console.log(result);
}
});
}
function complete() {
var item = $("#item_text").val().trim();
if (item.length == 0) {
alert('输入数据不能为空');
}
$.ajax({
url: "/complete",
method: 'GET',
data: {
item: item
},
success: function(result) {
console.log(result);
}
});
}
</script>
完整的 index.html 如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>待办列表</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
<script type="text/javascript">
$(function() {
$("#add").on('click', function(){
add();
});
$("#complete").on('click', function(){
complete();
});
});
function add() {
var item = $("#item_text").val().trim();
if (item.length == 0) {
alert('输入数据不能为空');
}
$.ajax({
url: "/add",
method: 'GET',
data: {
item: item
},
success: function(result) {
console.log(result);
}
});
}
function complete() {
var item = $("#item_text").val().trim();
if (item.length == 0) {
alert('输入数据不能为空');
}
$.ajax({
url: "/complete",
method: 'GET',
data: {
item: item
},
success: function(result) {
console.log(result);
}
});
}
</script>
</head>
<body>
<h1>待办列表</h1>
<form method="post" >
<p><input id="item_text" type="text" name="item" /></p>
<p><input id="add" type="submit" value="添加" /></p>
<p><input id="complete" type="submit" value="完成" /></p>
</form>
<ul><li>%</li></ul>
</body>
</html>
- 保存 index.html
- 给添加、完成按钮增加点击
- 点击添加的时候,执行待办事项添加。点击完成,完成待办事项
- 启动服务
F:\Github\Nodejs\todolist>node server.js
Server running at http://127.0.0.1:3000/
NodeJS 服务端增删改查
修改 server.js
- 服务端使用 set 存储待办事项
var todoSet = new Set();
- 如何解析 url 参数,使用 url 模块,示例代码如下
F:\Github\Nodejs\todolist>node
Welcome to Node.js v18.12.1.
Type ".help" for more information.
> require('url').parse('http://127.0.0.1:3000/')
Url {
protocol: 'http:',
slashes: true,
auth: null,
host: '127.0.0.1:3000',
port: '3000',
hostname: '127.0.0.1',
hash: null,
search: null,
query: null,
pathname: '/',
path: '/',
href: 'http://127.0.0.1:3000/'
}
> require('url').parse('http://127.0.0.1:3000/com?item=1')
Url {
protocol: 'http:',
slashes: true,
auth: null,
host: '127.0.0.1:3000',
port: '3000',
hostname: '127.0.0.1',
hash: null,
search: '?item=1',
query: 'item=1',
pathname: '/com',
path: '/com?item=1',
href: 'http://127.0.0.1:3000/com?item=1'
}
- 服务端处理不同 url 逻辑
var urlParse = parse(request.url);
var urlPath = urlParse.pathname;
switch (urlPath) {
case '/add':
var itemData = findItemData(urlParse);
if (itemData.length == 0) {
sendMsg(response, '输入数据有误');
}
add(itemData);
break;
case '/complete':
var itemData = findItemData(urlParse);
if (itemData.length == 0) {
sendMsg(response, '输入数据有误');
}
var res = complete(itemData);
sendMsg(response, res);
break;
}
- 完整代码
const http = require('http');
const fs = require('fs');
const parse = require('url').parse;
const hostname = '127.0.0.1';
const port = 3000;
var todoSet = new Set();
function send404(response) {
response.writeHead(404, {'Content-Type': 'text/plain'});
response.write('Error 404: resource not found.');
response.end();
}
function sendMsg(response, msg) {
}
function readFile(response, filePath) {
fs.readFile(filePath, (err, data) => {
if (err) {
return send404(response);
}
var html = data.toString();
html = html.replace('%', Array.from(todoSet).join('</li><li>'));
response.writeHead(200, {'Content-Type': 'text/html'});
response.end(html);
});
}
function add(itemData) {
todoSet.add(itemData);
}
function complete(itemData) {
// 判断代办事项是否已添加
if (!todoSet.has(itemData)) {
return itemData + '待办事项不存在';
}
if (todoSet.delete(itemData)) {
return itemData + '待办事项删除成功';
}
return itemData + '待办事项删除失败';
}
function findItemData(urlParse) {
if (urlParse.query.length > 0) {
var queryArray = urlParse.query.split('=');
if (queryArray.length >= 2) {
return queryArray[1];
}
}
return '';
}
const server = http.createServer((request, response) => {
var urlParse = parse(request.url);
var urlPath = urlParse.pathname;
switch (urlPath) {
case '/add':
var itemData = findItemData(urlParse);
if (itemData.length == 0) {
sendMsg(response, '输入数据有误');
}
add(itemData);
break;
case '/complete':
var itemData = findItemData(urlParse);
if (itemData.length == 0) {
sendMsg(response, '输入数据有误');
}
var res = complete(itemData);
sendMsg(response, res);
break;
}
var filePath = 'public/index.html';
var absPath = './' + filePath;
readFile(response, absPath);
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`)
})
效果图
index.html、server.js 保存好了之后,启动服务
F:\Github\Nodejs\todolist>node server.js
Server running at http://127.0.0.1:3000/
初始页面
输入 1111,点击添加
列表增加 1111
再继续增加一个 2222