1. Route selection Process
Handling different HTTP requests is a different part of our code, called routing.
So, let's create a module called routing next . We need to look at the HTTP request and extract the requested URL and the Get/post parameter from it.
Url.parse (String). Query | Url.parse (String). Pathname | | | | | -------------------------Http://localhost:8888/start?foo=bar&hello=world --- ----- | | | | QueryString (String) ["foo"] | | QueryString (String) ["Hello"]
2. Route selection Implementation Code
Create a new routing file belonging to the server side Router.js
1 //-----------------router.js--------------------------------2module.exports={3Loginfunction(req,res) {4Res.write ("I am the login method");5 },6Registerfunction(req,res) {7Res.write ("I am the method of registration");8 }9}
The service-side call route, as in the last lesson, "Nodejs Advanced 2--Function module invocation," called the string called function.
1 //---------4_router.js-----------2 varHTTP = require (' http ');3 varurl = require (' URL '));4 varRouter = require ('./router '));5Http.createserver (function(Request, response) {6Response.writehead, {' Content-type ': ' text/html; Charset=utf-8 '});7if(request.url!== "/favicon.ico"){8 varpathname = Url.parse (request.url). Pathname;//get the requested path9 Console.log (pathname);Tenpathname = Pathname.replace (/\//, ");//Replace the previous/ One Console.log (pathname); A Router[pathname] (request,response); -Response.End (' '); - } the}). Listen (8000); -Console.log (' Server running at Http://127.0.0.1:8000/');
We've used the URL of node's own module. Url.path (URLSTR): Converts a URL string to an object and returns.
3. Url.path (URLSTR) example
The following shows an example of two Url.parse
例1. url.parse(‘http://stackoverflow.com/questions/17184791‘).pathname
结果为:
"/questions/17184791"
Example 2:
1 varurl = require (' URL '));2 varA = Url.parse (' Http://example.com:8080/one?a=index&t=article&m=default ');3 Console.log (a);4 5 //Output Result:6 { 7Protocol: ' HTTP ' ,8Auth:NULL ,9Host: ' example.com:8080 ' ,TenPort: ' 8080 ' , OneHostname: ' example.com ' , AHash:NULL , -Search: '? A=index&t=article&m=default ', -Query: ' A=index&t=article&m=default ', thePathname: '/one ', -Path: '/one?a=index&t=article&m=default ', -HREF: ' Http://example.com:8080/one?a=index&t=article&m=default ' -}
4. Output HTML files to the page
For a general GET request, for example localhost/login we need to output a page login.html to the browser, what do we do?
First of all we have two new pages
1.login.html
1 <HTML>2 <Head>3 </Head>4 <Body>5 Login:6 <P>This is a paragraph</P>7 <H1>Style 1</H1>8 </Body>9 <HTML>
2.register.html
1 <HTML>2 <Head>3 </Head>4 <Body>5 Registration:6 <P>This is a paragraph</P>7 <H1>Style 1</H1>8 </Body>9 <HTML>
The way to read the file, we put it in the file models/file.js
1 //-------------models/file.js-------------------------2 varfs= require (' FS ');3module.exports={4ReadFilefunction(Path,callback) {//asynchronous read file, need to pass in callback function5Fs.readfile (Path,function(err, data) {6if(err) {7 Console.log (err);8}Else{9 callback (data);Ten } One }); AConsole.log ("Async Method Execution Complete"); - }, -Readfilesync:function(path) {//Synchronous Read thevardata = Fs.readfilesync (path, ' Utf-8 ')); -Console.log ("Synchronization Method execution Complete"); -returndata; - } +}
Router.js need to call the file read method, the two page HTML file read the content and output to response. It is important to note that Res.end () is the location of this sentence, and if you read the file asynchronously, you cannot put it in the server to create the block.
1 //-----------------router.js--------------------------------2 varFile = require ('./models/file '));3module.exports={4Loginfunction(req,res) {5 varcallback=function(data) {6 res.write (data);7 res.end ();8 }9File.readfile ('./views/login.html ', callback);//using asynchronous ReadTen }, OneRegisterfunction(req,res) { AvarData=file.readfilesync ('./views/register.html ');//using synchronous reads - res.write (data); - res.end (); the } -}
We re-run: node 4_router.js. In the browser input http://localhost:8000/login and http://localhost:8000/register, output the contents of the login.html and register.html pages.
Nodejs Advanced 3-routing processing