NodeJS implements the routing function instance code, and nodejs implements the routing instance
Previous
This article uses NodeJS to implement routing functions for complex applications
Structure
The project structure is as follows:
The Code is as follows:
Function
[Router. js]
// Load the required module var http = require ('HTTP '); var url = require ('url'); var fs = require ('fs '); var host = '2017. 0.0.1 '; var port = 8080; http. createServer (function (req, res) {var pathname = url. parse (req. url ). pathname; console. log ('request for '+ pathname +' stored ed. '); function showPaper (path, status) {var content = fs. readFileSync (path); res. writeHead (status, {'content-type': 'text/html; charset = UTF-8 '}); res. write (content); res. end ();} switch (pathname) {// 'homepage 'case'/': case'/home': showPaper ('. /view/home.html ', 200); break; // 'about' case'/about': showPaper ('. /view/about.html ', 200); break; // '2017 page 'default: showPaper ('. /view/404.html ', 404); break ;}}). listen (port, host );
2017404.html]
<!DOCTYPE html>
【About.html]
<!DOCTYPE html>
【Home.html]
<!DOCTYPE html>
Demo
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.