跟我学NodeJS(八)路由功能

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

var host = '127.0.0.1';
var port = 8888;

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;
         //'login页'
        case '/login':
            showPaper('./view/login.html',200);
            break;
        //'404页'
        default:
            showPaper('./view/404.html',404);
            break;                            
    }    
}).listen(port, host);

login:


<html>
<head>
    <meta charset="UTF-8">
    <title>login页面title>
head>
<body>
username:<input type="text" name="username" />
password:<input type="password" name="password" />
   <input type="submit" name="login" /> 
body>
html>

404:


<html>
<head>
    <meta charset="UTF-8">
    <title>404页面title>
head>
<body>
   404
body>
html>

home:


<html>
<head>
    <meta charset="UTF-8">
    <title>home页面title>
head>
<body>
home    
body>
html>

about:


<html>
<head>
    <meta charset="UTF-8">
    <title>home页面title>
head>
<body>
home    
body>
html>

你可能感兴趣的:(node-js)