node的HTPP请求

我们先写一个js文件:

require("http").createServer(function(req,res){
    res.writeHead(200,{'Content-Type':'text/html'});
    res.end('Helld <b>Word</b>');
    console.log("listening in 127.0.0.1 3000...");
}).listen(4000);

这个文件里面一定要加上那个:
'Content-Type':'text/html'

如果不加的话浏览器只会输出  Hello <b>Word</b>  而不是显示粗体的

 改成:

require("http").createServer(function(req,res){
    res.writeHead(200,{'Content-Type':'text/html'});
    res.write('Hello ');
    setTimeout(() => {
        res.end('Word');
    }, 500);
    console.log("listening in 127.0.0.1 3000...");
}).listen(4000);

就会过500ms打印word

 

图片的版本:

require("http").createServer(function(req,res){
    res.writeHead(300,{'Content-Type':'image/jpg'});
    var stream=require('fs').createReadStream('demo.jpg');
    stream.on('data',function(data){
        res.write(data);
    });
    stream.on('end',function(){
        res.end();
    });
}).listen(4000);

我们这里传过去一张图片

 

以一系列的数据块发送信息有以下好处:

1.高效的的内存分配。要是对每个请求在写入前都完全把图片信息读完(通过fs.readFile),在处理大量请求时会消耗大量内存。

2.数据一旦就绪就可以立刻处理写入

上述代码简化成:

require("http").createServer(function(req,res){
    res.writeHead(300,{'Content-Type':'image/jpg'});
    require('fs').createReadStream('image.jpg').pipe(res);
}).listen(4000);

这里我们实际上就是利用pipe把一个流对接到另一个流上(http.ServerResponse)

 


一个简单的表单处理服务器:

require("http").createServer(function(req,res){
    res.writeHead(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(''));//用join方法转化成字符串
}).listen(3000);

这里的join方法可以重点记一下,很好用的一个方法

我们输入了一个名字提交了以后发现:

后面多了一个url

为了让node对表单的提交事件进行正确的处理,我们需要学习关于处理请求和处理url的方法

 

很显然,当用户按下提交按钮的时候我们需要处理表单

 

继续:

我们需要使用到req.url和req.method两个变量

req.url就是网址的端口号后面的

req.method这里就是form标签上指定的method,具体有:

GET(默认)

POST

PUT

DELETE

PATCH(最新的)

浏览器会根据form标签的anciton指定的HTTP方法将表单数据发送出去

require("http").createServer(function (req, res) {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    if ('/' == req.url) {
        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(''));//用join方法转化成字符串
    } else if ('/url' == req.url && 'POST' == req.method) {//如果点击了提交的按钮
        var body='';
        req.on('data',function(chunk){
            body+=chunk;
        });
        req.on('end',function(){
            res.writeHead(200,{'Content-Type':'text/html'});
            res.end('<p>Content-Type:'+req.headers['content-type']+'</p>'//获取heasers里面 
                                                                     //content-type部分
            +'<p>Data:</p><pre>'+body+'</pre>');
        });
    }
}).listen(3000);

 

我们用body接收了输入的字符串

 

结果:

 

关于content-type可以参考http://www.runoob.com/http/http-content-type.html

我们再来了解一下querystring模块:

console.log(require('querystring').parse('name=Guillermo'));
console.log(require('querystring').parse('q=guillermo+rauch'));

模块将一个字符串解析成一个对象。

现在我们利用这个模块:

var qs=require("querystring");
require("http").createServer(function (req, res) {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    if ('/' == req.url) {
        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(''));//用join方法转化成字符串
    } else if ('/url' == req.url && 'POST' == req.method) {
        var body='';
        req.on('data',function(chunk){
            body+=chunk;
        });
        console.log(typeof(req.headers));
        req.on('end',function(){
            res.writeHead(200,{'Content-Type':'text/html'});
            // res.end('<p>Content-Type:'+req.headers['content-type']+'</p>'
            // +'<p>Data:</p><pre>'+body+'</pre>');
            console.log(qs.parse(body));
            res.end('<p>Your name is <b>'+qs.parse(body).name+'</b></p>');
        });
    }
}).listen(3000);

这里打印出来的是:

所以我们需要qs.parse(body).name

 

最后,我们健壮一下程序,如果没有匹配到这两个url,就显示:

else{
        res.writeHead(200,{'Content-Type':'text/html'});
        res.end('<b>Not Found</b>')
    }

 

OK,deal~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值