>  기사  >  웹 프론트엔드  >  nodejs를 사용하여 라우팅 기능 구현

nodejs를 사용하여 라우팅 기능 구현

青灯夜游
青灯夜游앞으로
2021-03-15 10:25:321969검색

이 글에서는 Node를 사용하여 보다 복잡한 애플리케이션 라우팅 기능을 구현하는 방법을 소개합니다. 도움이 필요한 친구들이 모두 참고할 수 있기를 바랍니다.

nodejs를 사용하여 라우팅 기능 구현

관련 추천: "nodejs tutorial"

structure

 프로젝트 구조는 다음과 같습니다

코드는 다음과 같습니다

Function

【라우터 .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

을 방문하세요. 프로그래밍 영상! !

위 내용은 nodejs를 사용하여 라우팅 기능 구현의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 cnblogs.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제