1, first solve the encapsulation of static Web server

1)

  • First, make a copy of the Web-server folder named Web-server-fengzhuang for encapsulation
  • Change common.js to routes.js
const fs = require("fs"); const url = require("url"); const path = require("path"); Var getFileMine = function (extname) {var data = fs.readfilesync ("./data/test.json"); Parse (data.tostring ()); return mimeObj[extname]; }; Static = function (req, res, staticPath) {// 1, static = function (req, res, staticPath) {// 2, static = function (req, res, staticPath); var pathname = url.parse(req.url).pathname; // console.log(url.parse(req.url)); Pathname = pathName == "/"? "/test.html" : pathname; Extname var extName = path.extName (pathname); // if (pathname! = "/favicon.ico") { fs.readFile("./" + staticPath + pathname, (err, data) => { if (err) { res.writeHead(404, { "Content-Type": 'text/html; charset="utf-8"' }); Res.end ("404 this interface does not exist "); } var mine = getFileMine(extname); res.writeHead(200, { "Content-Type": "" + mine + '; charset="utf-8"' }); res.end(data); }); }};Copy the code

2) App-1. Js also needs to be modified

var http = require("http"); // add routes.js const routes = require("./module/routes"); Http.createserver (function (req, res) {routes. Static (req, res, "static"); }) .listen(3001);Copy the code

3) Nodeapp1.js can start the service to check that the corresponding file type is correct

2, routing,

1)

  • Such as login/register page http://127.0.0.1:3001/login said said registration/admin said backstage management

2) delete 404 interface from routes.js because we need to continue to match the route down and add this sentence

if(! err){ var mine = getFileMine(extname); res.writeHead(200, { "Content-Type": "" + mine + '; charset="utf-8"' }); res.end(data); }Copy the code
  • App-1. Js starts doing judgment and matching operations
var http = require("http"); var url = require("url"); // add routes.js const routes = require("./module/routes"); Http.createserver (function (req, res) {routes. Static (req, res, "static"); Var pathName = url.parse(req.url).pathname; if (pathname == "/login") { res.writeHead(200, { "Content-Type": ' text/html ; charset="utf-8"' }); Res.end (" Execute login "); } else if (pathname == "/register") { res.writeHead(200, { "Content-Type": ' text/html ; charset="utf-8"' }); Res.end (" Perform registration "); } else if (pathname == "/admin") { res.writeHead(200, { "Content-Type": ' text/html ; charset="utf-8"' }); Res.end (" processed business logic "); } else { res.writeHead(404, { "Content-Type": ' text/html ; charset="utf-8"' }); Res.end (" page does not exist "); } }) .listen(3001);Copy the code
  • Routes. Js
// if (pathname! = "/favicon.ico") { fs.readFile("./" + staticPath + pathname, (err, data) => { // if (err) { // res.writeHead(404, { "Content-Type": 'text/html; charset="utf-8"' }); // res.end("404 does not exist "); // } if (! err) { var mine = getFileMine(extname); res.writeHead(200, { "Content-Type": "" + mine + '; charset="utf-8"' }); res.end(data); }}); }Copy the code
  • Nodeapp1.js: /login is valid but garbled
  • One more questionhttp://127.0.0.1:3001I can’t show it. Check it outFs.readfile () is an asynchronous method
  • I can change it hereSynchronization of fs. ReadFileSync ()
  • After the change, it looks like this
const fs = require("fs"); const url = require("url"); const path = require("path"); Var getFileMine = function (extname) {var data = fs.readfilesync ("./data/test.json"); Parse (data.tostring ()); return mimeObj[extname]; }; Static = function (req, res, staticPath) {// 1, static = function (req, res, staticPath) {// 2, static = function (req, res, staticPath); var pathname = url.parse(req.url).pathname; // console.log(url.parse(req.url)); Pathname = pathName == "/"? "/test.html" : pathname; Extname var extName = path.extName (pathname); // if (pathname! = "/favicon.ico") { try { var data = fs.readFileSync("./" + staticPath + pathname); if (data) { var mine = getFileMine(extname); res.writeHead(200, { "Content-Type": "" + mine + '; charset="utf-8"' }); res.end(data); } } catch (error) {} } };Copy the code
  • Restart Node app1.js and find that it is normalThe three routes are still in garbled state
  • I don’t want you to manually knock on the back and secretly change the top
if (pathname == "/login") { res.writeHead(200, { "Content-Type": ' text/html ; charset="utf-8"' }); Res.end (" Execute login ");Copy the code
  • After the restart, the problem is resolved nice

EJS template engine

1) Make a copy of web-server-fengzhaung and name it web-EJS

2) Search for EJS in npmjs.com and install the module NPM install EJS in web-EJS

3) Create new views under this folder to write a file login.ejs content is EJS template engine

4) Add a little content to app-1. Js

var ejs = require("ejs"); If (pathName == "/login") {var MSG = "database "; ejs.renderFile("./views/login.ejs", { msg: msg }, (err, data) => { res.writeHead(200, { "Content-Type": ' text/html ; charset="utf-8"' }); res.end(data); }); . }Copy the code

5) Execute node app1.js after startup

6) The database data can be directly displayed on the page

  • The nice thing about this is that the database changes and the page refreshes accordingly
  • Much of this syntax can be seen directly on ejS

7) Next we simulate an array retrieved from the database and render it on the page

  • Ejs says this
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Initial - scale = 1.0 "> < title > Document < / title > < / head > < body > < h2 > this is a landing page < / h2 > < h3 > < % = MSG % > < / h3 > < ul > < % for (var I = 0; i < tlist.length; i ++){%> <li><%=tlist[i].title%></li> <%}%> </ul> </body> </html>Copy the code
  • App-1.js says this
If (pathName == "/login") {var MSG = ""; var list = [ { title: "test111" }, { title: "test222" }, { title: "test333" }, { title: "test444" }, ]; ejs.renderFile( "./views/login.ejs", { msg: msg, tlist: list }, (err, data) => { res.writeHead(200, { "Content-Type": ' text/html ; charset="utf-8"' }); res.end(data); }); . }Copy the code
  • Then Node app1.js starts the service

  • So you’re going to have to go back to the documentation for the rest of this
  • Notice a pattern in the data section written in<% write it in the middle %>

4, Get request

1)

2) How do we get the value of get after the address? Page = 2 & id = 1?

For example, there’s a web site calledhttp://127.0.0.1:3001/news?page=2&id=1

  • Nice seems to make things a little bit easier with that
  • We tried to continue to improve this part of the feature

3) So let’s change it a little bit in app-1.js

If (pathName == "/news") {var query = url.parse(req.url).query; console.log(query); res.writeHead(200, { "Content-Type": ' text/html ; charset="utf-8"' }); res.end(query); . }Copy the code
  • Restart the node app – 1. Js and then write to http://127.0.0.1:3001/news? page=2&id=1
  • You can see the data

  • But what you’re printing out is a string and how do you convert it to an object?

  • node app-1.js

  • The console can see the results

  • So what do we think about data types?How do I know if it's a GET request?

5. Post requests

1) Let’s look at the post process in app-1.js with a slight change

2) Create a new form.ejs file under the Views folder

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, "> <title>Document</title> </head> <body> <form action="/doRegister" method="post"> <input type="text" name="username"> <br> <input type="password" name="password"> <br> <br> < form> < body> </ HTML >Copy the code
  • App-1. Js is slightly changed
Ejs. renderFile("./views/form.ejs", {}, (err, data) => { res.writeHead(200, { "Content-Type": ' text/html ; charset="utf-8"' }); res.end(data); });Copy the code
  • node app-1.js

You can see

3) Next question: How do I pass the POST value?

  • You need to make another page to get the post value
else if (pathname == "/doRegister") { res.writeHead(200, { "Content-Type": ' text/html ; charset="utf-8"' }); res.end("post ok");Copy the code

4) Native Node JS gets the value of post

} else if (pathname == "/doRegister") { // res.writeHead(200, { "Content-Type": ' text/html ; charset="utf-8"' }); // res.end("post ok"); Var postData = ""; req.on("data", (chunk) => { postData += chunk; }); req.on("end", () => { console.log(postData); res.end(postData); });});});Copy the code
  • node app-1.js