1. Show Dynamic Web pages
Another exciting time, you can use node to create a dynamic Web site, the principle is:
- Using placeholders in HTML templates
- Depending on the request path, determine the page that needs to be returned
- Determine the value of a placeholder in a static template based on the request parameters
- Match placeholders to real values using regular matches
- Again Res.write () to the browser's
The code is as follows:
//Server.jsvarHTTP = require ("http");varurl = require (' URL '));varRouter = require ('./router ')); Http.createserver (function(req, res) {if(Req.url!== '/favicon.ico ') {Pathname= Url.parse (Req.url). Pathname.replace (/\//, "); Console.log (pathname); Try{Router[pathname] (req, res); } Catch(e) {Console.log (' ERROR: ' +e); Res.writehead ($, {' Content-type ': ' Text/html;charset=utf-8 '}); Res.write (E.tostring ()); Res.end (); }; }}). Listen (3000); Console.log ("Server running at http:127.0.0.1:3000");
/** * router.js*/varFS = require (' FS ');varurl = require (' URL '));varQueryString = Require (' querystring ')); Module.exports={login:function(req, res) {varPost = '; Req.on (' Data ',function(chunk) {post+=Chunk; }); Req.on (' End ',function() {post=Querystring.parse (POST); Array= [' username ', ' password ']; Fs.readfile ('./login.html ',function(err, data) {if(Err) {Console.log (err); Res.writehead ($, {' Content-type ': ' Text/html;charset=utf-8 '}) Res.write (Err.tostring ()); Res.end (); } Else{Res.writehead ($, {' Content-type ': ' Text/html;charset=utf-8 '}) Data=data.tostring (); for(vari = 0; i < Array.Length; i++){ varReg =NewRegExp ("{{" +array[i]+ "}}", ' G '); Console.log (REG); Post[array[i]]= Post[array[i]] = = undefined? ‘‘:p Ost[array[i]]; Data=Data.replace (Reg, Post[array[i]]); Console.log (Post[array[i]); } res.write (data); Res.end (); }})}, register:function(req, res) {Fs.readfile ('. Register.html ',function(err, data) {if(Err) {Console.log (err); Res.writehead ($, {' Content-type ': ' Text/html;charset=utf-8 '}) Res.write (Err.tostring ()); Res.end (); return; } Else{Res.writehead ($, {' Content-type ': ' Text/html;charset=utf-8 '}); Res.write (data); Res.end (); })}, ShowImage:function(req, res) {Fs.readfile ('./test.png ',function(err, data) {if(Err) {Console.log (err); return; } Else{Console.log ("Start reading Pictures"); Res.writehead ($, {' Content-type ': ' Image/jpeg '}); Res.write (data); Res.end ();//It's going to be an error outside the Intermodulation function. } }) }}
<! DOCTYPE html>
Node Foundation 12: Dynamic Web page