美文网首页
nodejs简单服务器实现

nodejs简单服务器实现

作者: 逐悦 | 来源:发表于2016-10-18 15:06 被阅读19次

    我们要实现的是通过浏览器请求简单的服务器上的html文件

    直接上代码:

    //server.js
    "use strict"
    
    // 引用要使用的模块
    const http = require('http');
    const url = require('url');
    const fs = require('fs');
    const path = require('path');
    
    function start() {
        const host = '127.0.0.1';
        const port = 8081;
    
        http.createServer((req, res) => {
            //解析访问路径
            let pathname = url.parse(req.url).pathname;
            if(pathname === '/')  //判断是否是访问根目录,如果是则访问index.html
                pathname = 'index.html';
            rtnHtml(path.join(__dirname,pathname),res);
        }).listen({host, port});
    }
    
    //把数据传递到客户端
    function rtnHtml(filename,res){
      
        fs.readFile(filename,(err ,data)=>{
            if(err){
                res.writeHead(404,{"Content-Type":'text/html'});
            }else{
                // 以html文件内容类型返回客户端
                res.writeHead(200,{"Content-Type":'text/html'});
                res.write(data);
            }
            res.end();
        });
    }
    
    
    if(module.parent == null){
        // 执行
        start();
    }
    

    把两个辅助文件html加入到server.js所在的目录中 :

     index.html
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <title>Document</title>
    </head>
    <body>
        <h1>Hello World!</h1>
        <h3>据说,分辨一个人是不是程序员,要看他打字是否以;结尾</h3>
    </body>
    </html>
    
    
    //login.html
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <title>Document</title>
    </head>
    <body>
        
        <form action="http://127.0.0.1:8081" method="post">
            <input type="text" name="name" value="hello" />
            <input type="text" name="password" value="world" />
            <input type="submit" name="submit" value="提交" />
        </form>
    </body>
    </html>
    

    然后在浏览器中访问http://localhost:8081http://localhost:8081/login.html就可以了

    相关文章

      网友评论

          本文标题:nodejs简单服务器实现

          本文链接:https://www.haomeiwen.com/subject/nshtuttx.html