NodeJS implements the routing function instance code, and nodejs implements the routing instance

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.