Node.js 制作简易的服务器渲染留言页面

//note.js
var fs = require('fs');
var http = require('http');
var template = require('art-template');
var Url = require('url');
const {
    
     url } = require('inspector');
//获取时间的函数
function GetNowFormatDate(){
    
    
    var MyDate = new Date();
    var year = MyDate.getFullYear();
    var month = MyDate.getMonth();
    var day = MyDate.getDate();
    var h = MyDate.getHours();  // 0-23
    var m = MyDate.getMinutes(); 
    if ( m < 10 )  m = '0'+ m ;
    var s = MyDate.getSeconds();
    if( s < 10 ) s = '0' + s;
   
    var NowTime = year + '/' + month + '/' + day + '/' + h + ':' + m;
    return NowTime;
}

var content = [
 {
    
    
    name: 'Vodka',
    passage: '迄今为止的人生都大写着失败,但不妨碍我继续向前!',
    dateTime: GetNowFormatDate()
 },
 {
    
    
    name: 'Vodka',
    passage: '迄今为止的人生都大写着失败,但不妨碍我继续向前!',
    dateTime: GetNowFormatDate()
 },
 {
    
    
    name: 'Vodka',
    passage: '迄今为止的人生都大写着失败,但不妨碍我继续向前!',
    dateTime: GetNowFormatDate()
 },
 {
    
    
    name: 'Vodka',
    passage: '迄今为止的人生都大写着失败,但不妨碍我继续向前!',
    dateTime: GetNowFormatDate()
 },
 {
    
    
    name: 'Vodka',
    passage: '迄今为止的人生都大写着失败,但不妨碍我继续向前!',
    dateTime: GetNowFormatDate()
 },
 {
    
    
    name: 'Vodka',
    passage: '迄今为止的人生都大写着失败,但不妨碍我继续向前!',
    dateTime: GetNowFormatDate()
 }
];
/*
  当前应用的模块依赖项都声明在文档最上面,为了让目录结构统一清晰,html文件一般放在view视图中,
  其他静态资源一般放在public 目录,以供用户请求使用
*/

http.createServer(function(request,response){
    
    
   var url = request.url;
   //利用url.parse() 将url路径转换为便于操作的对象,第二个参数true 表示将查询(query 属性) 字符串转为一个对象  
   /*
      Url {
           protocol: 'http:',
           slashes: true,
           auth: null,
           host: '127.0.0.1:5000',
           port: '5000',
           hostname: '127.0.0.1',
           hash: null,
           search: '?Name=Vodka&comment=%E9%9D%9E%E5%B8%B8%E7%A5%9E%E5%A5%87',
           query: [Object: null prototype] { Name: 'Vodka', comment: '非常神奇' },
           pathname: '/form',
           path: '/form?Name=Vodka&comment=%E9%9D%9E%E5%B8%B8%E7%A5%9E%E5%A5%87',
           href: 'http://127.0.0.1:5000/form?Name=Vodka&comment=%E9%9D%9E%E5%B8%B8%E7%A5%9E%E5%A5%87'
        }
   */   
   var urlObj = Url.parse(request.url,true);
   //获取不包含后面查询字符串的路径部分  '/form' 
   var ObjPathName = urlObj.pathname;
   if( ObjPathName === '/'){
    
    
      //统一渲染页面
      fs.readFile('/web/Node/html/notemain.html',function(error,data){
    
    
        if(error){
    
    
            return response.end('Read Failure!');
        }else {
    
    
            return response.end(template.render(data.toString(),{
    
    
                //创建一个对象,用于渲染页面
                content: content
            }));
        }
    });
   }
   //indexOf , 返回参数字符串第一次出现的位置索引,没有则返回 -1 ;
   //这里是为了响应html页面中,具有外链属性的标签的再次request
   else if ( ObjPathName.indexOf('/web/Node/') === 0 ){
    
    
       //响应css请求,根据不同的url
        fs.readFile(url , function(error,data){
    
    
            if( error ){
    
    
                return response.end('Read Failure!');
            }else {
    
    
                return response.end(data);
            }
        });
   }else if(ObjPathName === '/web/post'){
    
    
        //响应填写页面的链接请求
        fs.readFile('/web/Node/html/post.html',function(error,data){
    
    
           if (error){
    
    
               return response.end('Read Failure!');
           }else {
    
    
               return response.end(data);
           }
        });
   }else if( ObjPathName === '/form'){
    
    
       //发送填写页面到主页面,并进行刷新
       fs.readFile('/web/Node/html/notemain.html',function(error,data){
    
    
            if(error){
    
    
                return response.end('Read Failure!');
            }else{
    
    
                // 输出包含表单值的数组对象的方法:console.log(urlObj.query);
                // 返回包含查询对象的JSON对象到相应页面中的方法: return response.end(JSON.stringify(urlObj.query));
                // 创建一个对象,转换 Url 中的 query 对象,在添加到自定义的 content 数组中
                var example = {
    
    };
                example.name = urlObj.query.Name ;
                example.passage = urlObj.query.comment;
                example.dateTime = GetNowFormatDate();
                content.unshift(example);
                //存储好数据之后, 就通过服务器让客户端重定向
                /*
                    1.设置临时重定向状态码: 302  , (永久状态码: 301)
                    2.在响应头中通过location 告诉客户端往哪里重定向, 客户端收到302码后,就会去响应头中找Location,
                    这就是自动跳转
                */
               response.statusCode = 302;
               response.setHeader('Location','/');
               response.end();
            }
       });
   }
   else {
    
    
       //其他错误的url请求路径,统一当404页面处理
       fs.readFile('/web/Node/html/404.html',function(error,data){
    
    
           if(error){
    
    
               return response.end('Read failure!');
           }else {
    
    
               return response.end(data);
           }
       });
   }
})
.listen(5000,function(){
    
    
    console.log('Server had been started , you can access from ip: http://127.0.0.1:5000');
});
notemain.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>NoteMain</title>
    <!-- 浏览器收到HTML 响应内容后,就会从上到下依次解析,
         当在解析过程中,如果发现:  
            link , script , audio ,vedio,img ,iframe 等(外链资源)带有 src 或 href (link) 属性标签的时候,
            浏览器会自动为这些资源再次发起新的请求
    -->
    <link rel="stylesheet" href="\web\Node\css\notemain.css" >
    <script src="/Node/node_modules/art-template/lib/template-web.js"></script>
</head>
<body>
    <div class ="majorBody" id="majorBody">

        <div class ="header" id="header">
            Comment Page: 
            <span class="headAside">Welcome to write your comment!</span>
        </div>

        <div class ="button" >
           <button class="write" id="writeButton"><a href="/web/post">write</a></button>
        </div>

        <div class ="comment" id="commentPage">
         <ul class="contentList" id="contentList">
             <!-- 遍历渲染页面 -->
          {
   
   { each content }}
           <li class="content" id="content">
               <a href="/web/post" id="noteLink">{
   
   { $value.name }}说: " {
   
   { $value.passage }} " </a>
               <p>{
   
   { $value.dateTime }}</p>
           </li>
           {
   
   { /each }}
         </ul>
        </div>

    </div>
    
    
    
</body>
</html>
post.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Post</title>
    <link rel="stylesheet" href="/web/Node/css/post.css">
</head>
<body>
    <!-- 
        表单的提交分为:
           1.默认提交
           2.表单的异步提交
           3.action 包含的就是表单提价的地址,url请求的地址 , method 分为 get , post
           4.get和post的区别:
              区别1:get请求的参数会暴露在浏览器的地址栏中,不安全,post请求的参数不会显示在地址栏中,相对安全。
              
              例:地址栏中显示 www.handleForm.html?username=aaa&password=123
              
              get 
              
              post 
              
              区别2:get请求的参数长度有限制(通常和浏览器相关)
              
              post请求的参数理论上长度无限制
           
     -->
    <form action="/form" method="GET">
       <div class="MajorBody" id="MajorBody">
           <div class="Header" id="Header">
              <a href="/" class="majorLink">首页</a>
              <span>发表言论</span>
           </div>
    
           <div class="AddressName" id="AddressName">
             <input type="text" name="Name" class="NameText" id="NameText" placeholder="Please input your name!">
           </div>
    
           <div class="LeaveBoard">
              <textarea type="text" name="comment" class="ContentText" id="ContentText" cols="40" rows="10" required minlength ="2" maxlength = "20" id="ContentText" placeholder="Please input your comment."></textarea>
           </div>
    
           <div class="Submit" id="Submit">
            <button class="SubmitButton" id="SubmitButton" type="submit">Submit</button>
           </div>
        </div>
    </form>
</body>
</html>

在这里插入图片描述

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Vodka688/article/details/115261468