Front
Following the previous section, today we will complete the development of a background server using Node to implement a simple user review community. You can see the effect first.
start
- Create a project folder comment-list, create a new public folder in it, and the public folder stores the resources we allow the client to access, which is open here. The app.js file is our server code.
In the index.html file, the content of the homepage of the website is placed. Here, bootstrap framework is used to build it quickly. You can recruit some false data first, so that the page can be rendered and then see the effect. Core code:
<ul class="list-group comment-list"> {{each comments}} <li class="list-group-item">{{$value.content}}<span class="time">{{$value.time}}</span> <span class="name">{{$value.name}}</span></li> {{/each}} </ul>
js template grammar is used here, and template strings will be rendered into real data in server-side code later. When the user visits the website root directory, the server parses the rendering index. HTML using the template engine, and returns the real HTML string to the browser for parsing. index.html will use Outer Link Style Files and Outer Link Script Files. Keep in mind that the file address here cannot write relative paths. You must write url addresses. See below:
<link rel="stylesheet" href="/public/lib/bootstrap/dist/css/bootstrap.css"> <link rel="stylesheet" href="/public/css/index.css"> .... <script src="/public/js/index.js"></script>
File addresses begin with / public / where / represents the root path of the request. Browsers automatically replace the request with http://127.0.0.1:3000/.
404.html is mainly used to handle user requests for non-existent resources, we can do it with friendship prompts.
post.html is mainly a comment page, which also uses bootstrap to build quickly. At the same time, we should pay attention to the file path problem. Here is a form for collecting user comments and submitting them to the background for processing. Form submission data can be assigned a submission address according to the action attribute in the form tag. When the submission button is clicked, the data will be sent to the specified address, which can be received and processed by the server. The core code is as follows:
<form action="/comment" method="GET" role="form" class="comment-form"> <legend>Commenting on</legend> <div class="form-group"> <label for="name">Your name:</label> <input type="text" name="name" class="form-control" id="name" placeholder="Please enter your name." required maxlength="10" minlength="2"> </div> <div class="form-group"> <label for="content">Comments:</label> <textarea name="content" id="content" class="form-control" rows="6" required minlength="5" maxlength="10"></textarea> </div> <button type="submit" class="btn btn-primary">Submission</button> </form>
- Write the server-side code app.js
app.js introduces http service construction core module in node, fs file operation module and urlurl address resolution module. The art-template third-party package is mainly used for the server-side template engine to parse the just index.html template string. We should pay attention to the parse method in the url core module, which can parse a url address containing query strings into an object, through which we can easily get the data submitted by the user form, that is, the specific content of the query string. You can see the following demonstration:
The second parameter, true, is passed through url.parse(), which converts the query query string into an object for subsequent acquisition of submitted data.
We also use the concept of server-side redirection. When the user submits the form data, the page will jump to / comment address. We need to set the response status code in the server-side request processing function: 302, and tell the browser the redirected address through the response header location attribute. The code is as follows:
res.statusCode = 302 // Set the response status code to 302 (redirection) res.setHeader('location', '/') // Set the response header location to tell the browser to redirect the address
The core code in app.js is as follows:
http.createServer((req, res) => { let obj = url.parse(req.url, true) // Get the URL object parsed by the URL template, pass in the second parameter "true", and convert the query string submitted by the form form into the object. let pathname = obj.pathname let query = obj.query if (pathname === '/') { fs.readFile('./public/views/index.html', (err, data) => { if (err) { return res.end('404 NOT FOUND') } let htmlStr = template.render(data.toString(), { comments: comments }) res.end(htmlStr) }) } else if (pathname.indexOf('/public/') === 0){ fs.readFile('.'+pathname, (err, data) => { if (err) { return res.end('404 NOT FOUND') } res.end(data) }) } else if (pathname ==='/post') { fs.readFile('./public/views/post.html', (err, data) => { if (err) { return res.end('404 NOT FOUND') } res.end(data) }) } else if (pathname === '/comment') { res.statusCode = 302 // Set the response status code to 302 (redirection) res.setHeader('location', '/') // Set the response header location to tell the browser to redirect the address if (query.name) { query.time = '2015-5-10' comments.unshift(query) } // Placing the user's manual input'/ comment'causes the query to be empty res.end() // End response, no less } else { fs.readFile('./public/views/404.html', (err, data) => { if (err) { return res.end('404 NOT FOUND') } res.end(data) }) } }).listen(3000, () => { console.log('running...') })
- After opening the server, you can post comments happily.
The complete code can see the GitHub address: Here
Explain
This article is about my Node.js course materials from zero to one. If you think it's helpful to you, you might as well give me a star. I will keep updating the relevant series of courses.
Project address: GitHub