1. 文档结构
2. code 代码 aap.js
var http
= require('http')
var fs
= require('fs')
var template
= require('art-template')
var url
= require('url')
var comments
= [{
name
: '张四',
message
: '今天是个好日子',
dataTime
: '2020.03.03'
},
{
name
: '张三',
message
: '今天是个好日子',
dataTime
: '2020.03.03'
}
]
http
.createServer(function(req
, res
) {
var parseObj
= url
.parse(req
.url
, true)
var pathname
= parseObj
.pathname
if (pathname
== '/') {
fs
.readFile('./views/index.html', function(err
, data
) {
if (err
) {
return res
.end('404 not found')
} else {
var htmlstr
= template
.render(data
.toString(), {
comments
: comments
})
res
.end(htmlstr
)
}
})
} else if (pathname
=== '/post') {
fs
.readFile('./views/post.html', function(err
, data
) {
if (err
) {
return res
.end("404 non found")
}
res
.end(data
)
})
} else if (pathname
=== '/pinglun') {
var comment
= parseObj
.query
comment
.dataTime
= '2020-11-02'
comment
.message
= (comment
.message
).trim()
comments
.unshift(comment
)
res
.statusCode
= 302
res
.setHeader('Location', "/")
res
.end()
} else if (pathname
.indexOf('/public/') === 0) {
fs
.readFile('.' + pathname
, function(err
, data
) {
if (err
) {
return res
.end("404 non found")
}
res
.end(data
)
})
} else {
return res
.end("404 non found")
}
})
.listen(3000, function() {
console
.log("running...");
})
index.html
<!DOCTYPE html
>
<html
>
<head
>
<meta charset
="utf-8">
<title
></title
>
<link rel
="stylesheet" type
="text/css" href
="/public/css/bootstrap.css" />
</head
>
<body
>
<!-- http
://127.0.0.1:3000/node
/feedback
/node_modules
/bootstrap
/dist
/css
/bootstrap
.css
-->
<div
class="page-header">
<h1
>请输入留言
</h1
>
<a href
="/post">发表留言
</a
>
</div
>
<div
class="comments container">
<ul
class="list-group">
{{each comments
}}
<li
class="list-group-item">{{$value
.name
}}说:
{{$value
.message
}}
<span
class="pull-right">{{$value
.dataTime
}}</span
>
</li
>
{{/each
}}
</ul
>
</div
>
</body
>
</html
>
post.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" type="text/css" href="/public/css/bootstrap.css" />
</head>
<body>
<div class="page-header">
<h1>请输入评论</h1>
<a href="/">回到首页</a>
</div>
<div class="header container">
<!-- //表单提交默认必须有name属性
1.表单提交分为两种
默认的提交 和表单异步提交
action 就是表单提交的地址, 就是请求的url地址
method请求的方法 get post
-->
<form action="/pinglun" method="get">
<div class="form-group">
<label for="input_name"> 你的大名:</label>
<input type="text" name='name' class="form-control" id="ecampleInputEmaill" placeholder="请写入你的姓名">
</div>
<div class="form-group">
<label for="textarea_message"> 留言内容:</label>
<textarea class="form-control" name='message' rows="10" cols="80" id="textarea_message" required minlength='5'>
</textarea>
</div>
<button type="submit" class="btn btn-default">发表</button>
</form>
</div>
</body>
</html>
注意: 这里依赖使用了 art-template Bootstrap(这个不是必要,可以自己写)
^-^ 笔记仅作为学习交流使用,如有异议请私信楼主删除。