首页 > 语言 > JavaScript > 正文

了不起的node.js读书笔记之node的学习总结

2024-05-06 14:48:51
字体:
来源:转载
供稿:网友

这周做项目做得比较散(应该说一直都是这样),总结就依据不同情境双开吧~这篇记录的是关于node的学习总结,而下一篇是做项目学到的web前端的知识。

1.HTTP篇

  node的HTTP模块在第一篇时接触过,这里来学习几个例程中出现的API。

代码如下:
var qs = require('querystring');

require('http').createServer(function(req, res){
    if('/' == req.url){
        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(''));
    }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('<b>Your name is <b>' + qs.parse(body).name + '</b></p>');
        });
    }else{
        res.writeHead(404);
        res.end('not found');
    }
 }).listen(3000);

  creatServer([requestListener])函数的参数是一个回调函数function(req, res),其中的req(请求request)是http.IncomingMessage的一个实例,res(响应)则是http.ServerRrsponse的实例。

  我们用到了res的url、method字符串和两个方法writeHead、end。顾名思义,url就是记录HTTP的URL(主机名后面所有的东西),method就是记录HTTP响应的方法。

  writeHead(statusCode, [reasonPhrase], [headers])用来发送一个http响应头信息,此方法只有当消息到来时才被调用一次,并且必须在end这一类方法之前调用。如果你反而为之,先调用了write(chunk, [encoding])或者end([data], [encoding])方法,系统会自动记录一个不易见、易变的(总之不好的)响应头内容并调用writeHead这个方法。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选