Home >Web Front-end >JS Tutorial >How to use nodejs to implement routing function

How to use nodejs to implement routing function

青灯夜游
青灯夜游forward
2021-03-02 10:00:482092browse

This article will introduce to you how to use node to implement more complex application routing functions. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

How to use nodejs to implement routing function

Related recommendations: "nodejs tutorial"

Structure

The project structure is as follows

The code is as follows

##Function

【router.js】

// 加载所需模块
var http = require('http');
var url = require('url');
var fs = require('fs');

var host = '127.0.0.1';
var port = 8080;

http.createServer(function(req,res){
    var pathname = url.parse(req.url).pathname;
    console.log('Request for ' + pathname + ' received.');
        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){
        //'首页'
        case '/':
        case '/home':
            showPaper('./view/home.html',200);
            break;
        //'about页'
        case '/about':
            showPaper('./view/about.html',200);   
            break;
        //'404页'
        default:
            showPaper('./view/404.html',404);
            break;                            
    }    
}).listen(port, host);

【404.html】

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
404    
</body>
</html>

【about.html】

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
about    
</body>
</html>

【home.html】

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
home    
</body>
</html>

Demo

##For more programming-related knowledge, please visit:

Introduction to Programming

! !

The above is the detailed content of How to use nodejs to implement routing function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete