Learn about Node.js and leave a simple message in this case

What do you think Node.js is for the front end when you haven't officially learned Node.js yet?

Will Node.js be considered a framework?Think this is a fast, concise JavaScript framework like Jquery?Anyway, I thought so at first because it had a.Js behind it.

Then when you officially start contacting Node.js, you find out how foolish you are.After entering the official website of Node.js, I read the introduction of Node before I found that Node and Js are so fierce.

The official sentence for Node.js is simply: (Node.js?, is a JavaScript runtime build on Chrome's V8 JavaScript engine .) Node.js is a JavaScript runtime based on the Chrome V8 engine.(

After reading this introduction, I was initially confused because I didn't know what to call the JavaScript runtime based on the Chrome V8 engine at all, and then I looked at the blogs of the big guys to see how they understood Node.js, I had a rough idea of Node.js in my mind.Node.js is a tool that runs JavaScript code on the server based on the Chrome V8 engine.This is to provide an environment for JavaScript to run on the server side.

After learning about Node.js, I started to find a simple instructional video online to learn Node.js and made a simple message This case

app.js (this JS script is run on the server side and does not have a DOM BOM unlike the browser's js)

  1 var http = require('http')
  2 var fs = require('fs')
  3 var template = require('art-template')
  4 var url = require('url')
  5 // silly-datetime Module can get current time
  6 var time = require('silly-datetime')
  7 var comments =[
  8     {
  9         name: 'Zhang San',
 10         message: 'It's a nice day today!',
 11         dateTime: '2015-10-16 22:17'
 12     },
 13     {
 14         name: 'Li Si',
 15         message: 'It's a nice day today!',
 16         dateTime: '2015-10-16 18:30'
 17     },
 18     {
 19         name: 'WangTwo',
 20         message: 'It's a nice day today!',
 21         dateTime: '2015-10-16 15:12'
 22     },
 23     {
 24         name: 'Chen Chen',
 25         message: 'It's a nice day today!',
 26         dateTime: '2015-10-16 10:31'
 27     },
 28     {
 29         name: 'Two Dogs',
 30         message: 'It's a nice day today!',
 31         dateTime: '2015-10-16 8:42'
 32     }
 33 ]
 34 // For us, it just needs to be decided if your request path is /pinglun Then I thought your request for a form came
 35 http.createServer(function(req,res) {
 36     // Use url.parse The method resolves the path to an operable object, with the second parameter true Indicates that the query string is converted directly to an object (by query Attribute to access)
 37     var parseObj = url.parse(req.url, true)
 38     // Get the part of the path separately that does not contain the query string (the path does not contain ? Afterwards)
 39     var pathname = parseObj.pathname
 40     if( pathname === '/') {
 41         fs.readFile('./views/index.html', function(err,data) {
 42             if(err) {
 43                 return res.end('404 Not Found')
 44             }else {
 45                 var htmlStr = template.render(data.toString(),{
 46                     comments:comments
 47                 })
 48                 res.end(htmlStr)
 49             }
 50         })
 51     // /public Whole public Resources in the directory are allowed to be accessed 
 52     // .indexOf()Method      Detect Request Address url Is there any /public initial ===0    If there is code executing inside
 53     // For example:     The request path is: http://127.0.0.1:3000/public/...... 
 54     }else if(pathname === '/post') {
 55         fs.readFile('./views/post.html', function(err,data) {
 56             if(err) {
 57                 return res.end('404 Not Found')
 58             }else {
 59                 res.end(data)
 60             }
 61         })
 62     }else if(pathname.indexOf('/public/') === 0) {
 63         // /public/css/main.css
 64         // /public/js/main.js
 65         // /public/lib/jquery.js
 66         // Unified Processing:
 67         //    If the request path is /public/ At the beginning, I think you want to get public A resource in
 68         //    So we can directly read the request path as a file path
 69 
 70         fs.readFile('.' + pathname, function(err,data) {
 71             if(err) {
 72                 return res.end('404 Not Found')
 73             }else {
 74                 res.end(data)
 75             }
 76         })
 77     }else if(pathname === '/pinglun') {
 78             //    1. Get data submitted by the form parseObj.query
 79             //    2. Add the current time and date to the data object and store it in the array
 80             //    3. Allow user redirection to jump to home page /
 81             //       When the user re-requests / At that time, the data in my array has changed, so the pages the user sees have changed
 82             var comment = parseObj.query
 83             // Get the current time
 84             comment.dateTime = time.format(new Date(), 'YYYY-MM-DD HH:mm')
 85             // .push()Method appends to the end of the array    .unshift()Method appends to the beginning of the array
 86             comments.unshift(comment)
 87             // comments.push(comment)
 88 
 89             // Now that the server has stored the data, the next step is for the user to request it again / Home page, you can see the latest message
 90 
 91             // How do I redirect clients through the server?
 92             //    1. Status code set to 302 temporary redirection
 93             //        statusCode
 94             //    2. Pass in Response Header Location Tell clients where to redirect
 95             //        setHeader
 96             // If the client finds that the status code for the response received from the server is 302, it automatically goes to the response header to look for it Location ,Then make a new request for the address
 97             // So you can see the client jump automatically   
 98             res.statusCode = 302
 99             // Go and ask for the path / Page of 
100             res.setHeader('Location', '/')
101             res.end()
102     }
103     else {
104         // All others were processed to 404 and could not be found
105         fs.readFile('./views/404.html', function(err,data) {
106             if(err) {
107                 return res.end('404 Not Found')
108             }else {
109                 res.end(data)
110             }
111         })
112     }
113 })
114 .listen(3000, function() {
115     console.log('Server started successfully, you can http://127.0.0.1:3000/for access');
116 })

The index.html page is the first page to leave a message for this case (clicking to post a message will jump to the post.html page)

 1 <!DOCTYPE html>
 2 <!-- saved from url=(0027)http://192.168.150.76:3000/ -->
 3 <html lang="en">
 4 <head>
 5   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 6   <title>Message Book</title>
 7   <link rel="stylesheet" href="/public/lib/bootstrap/bootstrap.css">
 8   <link rel="stylesheet" type="text/css"
 9      href="chrome-extension://fidicgekecdkdmkjghdgadgdmcfodfid/themes/default/content.css">  
10 </head>
11 <body>
12   <!-- <img src="/public/img/ab3.jpg" style="width:189px; height:126px"> -->
13   <div class="header container">
14     <div class="page-header">
15       <h1>Example page header <small>Subtext for header</small></h1>
16       <!-- <a class="btn btn-success" href="http://192.168.150.76:3000/post ">Post a message </a> -->
17       <a class="btn btn-success" href="/post">Post a message</a>
18     </div>
19   </div>
20   <div class="comments container">
21     <ul class="list-group">
22       <!-- <li class="list-group-item">1</li>-->
23       <!-- template engine -->
24       {{each comments}}
25         <li class="list-group-item">{{$value.name}}Say:{{$value.message}}<span class="pull-right">{{$value.dateTime}}</span></li>
26       {{/each}}
27     </ul>
28   </div>
29 </body>
30 </html>

post.html is the page where messages are written (clicking Publish will update the published content on the first page and jump to the first page to view the updated page when you have finished filling out the message)

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4   <meta charset="UTF-8">
 5   <title>Document</title>
 6   <link rel="stylesheet" href="/public/lib/bootstrap/bootstrap.css">
 7 </head>
 8 <body>
 9   <div class="header container">
10     <div class="page-header">
11       <h1><a href="/">home page</a> <small>Comment</small></h1>
12     </div>
13   </div>
14   <div class="comments container">
15     <form action="/pinglun" method="get">
16       <div class="form-group">
17         <label for="input_name">Your name</label>
18         <input type="text" class="form-control" required minlength="2" maxlength="10" id="input_name" name="name"
19           placeholder="Please write your name">
20       </div>
21       <div class="form-group">
22         <label for="textarea_message">Message</label>
23         <textarea class="form-control" name="message" id="textarea_message" cols="30" rows="10" required minlength="5"
24           maxlength="20"></textarea>
25       </div>
26       <button type="submit" class="btn btn-default">Publish</button>
27     </form>
28   </div>
29 </body>
30 </html>

404.html (Nothing to Say)

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4   <meta charset="UTF-8">
 5   <title>404</title>
 6 </head>
 7 <body>
 8   <h1>404 The page you visited is lost...</h1>
 9 </body>
10 </html>

Start app.js using your computer's cmd (command prompt) (this is equivalent to opening a web server)

You can see the index.html page on browser access by http://127.0.0.1:3000/ or by filling in the ip address of your machine

 

Click to post.html after posting a message

 

Clicking Publish will automatically jump to the index.html page and the message will be updated

This is the basic function of the whole message case, and I also follow other people's teaching step by step to achieve the basic sensory function, just like the database to save data, but through this case, I will have a better understanding of Node.js.

 

                                                             2019-12-01 12:40:34

Keywords: Javascript JQuery Attribute Web Server

Added by kujtim on Thu, 05 Dec 2019 04:49:46 +0200