读<了不起的Node.js>-11.一个简单的web服务器

  • 一个表单项目,获取表单提交信息,展示在网页上
  • 用原生node写网页是真的麻烦

创建模块

  • 老套路 先创建模块

输出表单

const http = require('http');

http.createServer(function (req, res) {
    res.writeHeader(200, {'Content-Type': 'text/html'});
    res.end([
        '<form method="post" action="/url">',
        '<h1>My form</h1>',
        '<fieldset>',
        '<label>Personal Information</label>',
        '<p>What is your name?</p>',
        '<input type="text" name="name">',
        '<p><button>Submit</button></p>',
        '</form>'
    ].join(''));
}).listen(3000);

  • 注意为了让html结构更加清楚,我们把响应文本内容写在一个数组内,再用数组的jion的方法将其转换为字符串
  • 需要注意的是<form>标签中有/url以及post方法,另外输入框内还有个叫name的名字
  • 下面是运行效果
1533544513193.png
  • 当我们输入内容提交以后注意地址栏的变化
1533544546492.png
  • 提交以后URL变了,不过响应结果是一样的,为了能让node能够对表单提交的请求做出正确的处理,这里需要学习关于检测请求方法和URL的相关内容

method和URL

  • 按逻辑,当我们进行提交的时候需要给用户呈现一个不一样的东西,这个时候我们需要处理表单

  • const http = require('http');
    
    http.createServer(function (req, res) {
        if ('/' == req.url) {
            res.writeHeader(200, {'Content-Type': 'text/html'});
            res.end([
                '<form method="post" action="/url">',
                '<h1>My form</h1>',
                '<fieldset>',
                '<label>Personal Information</label>',
                '<p>What is your name?</p>',
                '<input type="text" name="name">',
                '<p><button>Submit</button></p>',
                '</form>'
            ].join(''));
        } else if ('/url' == req.url) {
            res.writeHeader(200, {'Content-Type': 'text/html'});
            res.end(`you sent a ${req.method} request`)
        }
    
    }).listen(3000);
    
    
  • 这个时候我们直接访问是没有什么变化的,当我们直接访问/url以后就会跳转
1533545092697.png
  • 当我们提交以后就会
1533545228321.png
  • 如上所示,我们这里接触了两个变量 URL 和 method
  • Node会将主机名后所有的内容都放在url属性中
  • 关于method有几种不同的方法
    • GET
    • POST
    • PUT
    • DELETE
    • PATCH

数据

  • 当发送html 的时候,需要随着响应体定义Content-Type头信息

  • const http = require('http');
    
    http.createServer(function (req, res) {
        if ('/' == req.url) {
            res.writeHeader(200, {'Content-Type': 'text/html'});
            res.end([
                '<form method="post" action="/url">',
                '<h1>My form</h1>',
                '<fieldset>',
                '<label>Personal Information</label>',
                '<p>What is your name?</p>',
                '<input type="text" name="name">',
                '<p><button>Submit</button></p>',
                '</form>'
            ].join(''));
        } else if ('/url' == req.url && 'POST' == req.method) {
            let body = '';
            req.on('data',function (chunk) {
                body += chunk;
            });
            req.on('end',function () {
                res.writeHeader(200,{'Content-Type':'text/html'})
                res.end('<p>Content-Type:' + req.headers['content-type'] + '</p>' + '<p>Date:</p><pre>' + body + '</pre>');
                
            });
        }
    
    }).listen(3000);
    
    
  • 我们监听了data 和 end 事件,创建了一个body 自出穿用来接收数据块,仅当end 事件触发时, 我们就知道数据接收完全了

  • 之所以可以这样逐块接收数据,因为node允许在数据到达服务器时就可以对其进行处理,因为数据是以不同的TCP包到达服务器的,这和显示情况也完全匹配,我们现货区一部分数据,然后在某个时刻在获取其余的数据

  • 1533546078287.png
  • 1533551136370.png
  • 当我们在进行搜索的时候,,url中高亮的那部分为q=<search term>

  • 搜索部分的url和表单内容一样都是经过编码的,也就解释了为什么Content-Type为urlencoded

  • 这部分URL片段又被称为查询字符串

    • node提供了一个querystring的模块,可以方便的对这类字符串进行解析,这样我们就可以想处理头信息一样对其进行处理,下面是例子\
1533551437504.png

输出内容

1533551447887.png
  • 如图所示, querystring模块讲一个字符串解析成一个对象,这个解析处理方式和node解析headers消息的方式类似,node将http请求数据中得headers信息从字符串解析成一个方便处理的headers对象

整合

  • 现在我们要解析发送来的数据并展示出来
  • 这里我们用querystring parse 方法去解析
const http = require('http');
const qs = require('querystring');

http.createServer(function (req, res) {
    if ('/' == req.url) {
        res.writeHeader(200, {'Content-Type': 'text/html'});
        res.end([
            '<form method="post" action="/url">',
            '<h1>My form</h1>',
            '<fieldset>',
            '<label>Personal Information</label>',
            '<p>What is your name?</p>',
            '<input type="text" name="name">',
            '<p><button>Submit</button></p>',
            '</form>'
        ].join(''));
    } else if ('/url' == req.url && 'POST' == req.method) {
        let body = '';
        req.on('data',function (chunk) {
            body += chunk;
        });
        req.on('end',function () {
            res.writeHeader(200,{'Content-Type':'text/html'})
            res.end('<p>Your name is <b>'+ qs.parse(body).name+'</b></p>');

        });
    }

}).listen(3000);

  • 效果
  • 1533557405305.png

让程序更健壮

  • 这里有一个问题,如果URL没有匹配到任何判断条件怎么办
  • 解决这个问题我们可以在服务器不知道怎么处理该请求的时候,发送404给客户度阿女
  • 还有别的解决办法 但是这里我们采用书上说的方法来解决
const http = require('http');
const qs = require('querystring');

http.createServer(function (req, res) {
    if ('/' == req.url) {
        res.writeHeader(200, {'Content-Type': 'text/html'});
        res.end([
            '<form method="post" action="/url">',
            '<h1>My form</h1>',
            '<fieldset>',
            '<label>Personal Information</label>',
            '<p>What is your name?</p>',
            '<input type="text" name="name">',
            '<p><button>Submit</button></p>',
            '</form>'
        ].join(''));
    } else if ('/url' == req.url && 'POST' == req.method) {
        let body = '';
        req.on('data',function (chunk) {
            body += chunk;
        });
        req.on('end',function () {
            res.writeHeader(200,{'Content-Type':'text/html'})
            res.end('<p>Your name is <b>'+ qs.parse(body).name+'</b></p>');

        });
    } else {
        res.writeHeader(404);
        res.end('Not found')
    }

}).listen(3000);

  • 效果
  • 1533557651911.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容