Home > Web Front-end > JS Tutorial > body text

Detailed explanation of nodeJS implementation of routing function examples

零下一度
Release: 2017-06-26 11:31:27
Original
1485 people have browsed it

Previous words

This article will use NodeJS to implement the routing function of more complex applications

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);
Copy after login

【404.html】

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
404    
</body>
</html>
Copy after login

【about.html】

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>about    
</body>
</html>
Copy after login

【home.html】

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>home    
</body>
</html>
Copy after login

Demo

##

The above is the detailed content of Detailed explanation of nodeJS implementation of routing function examples. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!