构建 Node Web ToDoList 程序

构建 Node Web ToDoList 程序

本文是《Node.js 实战》读书笔记。

node 中 HTTP请求生命周期

  1. HTTP客户端,发起HTTP请求
  2. Node 接受连接,以及发送给HTTP服务器的请求数据
  3. HTTP 服务器解析完成HTTP头,将控制权转交给请求回调函数
  4. 请求回调,执行业务逻辑
  5. 响应通过HTTP服务器送回去。由它为客户端构造格式正确的HTTP响应

Hello world 示例:

var http = require('http');
var Server = http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
});
Server.listen(3000);
console.log("服务器运行在:http://localhost:3000");

读取设置响应头

方法:

  • res.setHeader(field, value)
  • res.getHeader(field)
  • res.removeHeader(field)

设置状态码

方法:
res.statusCode = 200

构建RESTful Web服务

使用POST、GET、DELETE、PUT实现一个命令行的TODOLIST

var http = require('http');
var url = require('url');
var items = [];

var server = http.createServer(function (req, res) {
    switch (req.method) {
        case 'POST':
            var item = '';
            req.setEncoding('utf8');
            req.on('data', function (chunk) {
                item += chunk
            });
            req.on('data', function () {
                items.push(item);
                res.end('OK\n');
            });
            break;
        case 'GET':
            var body = items.map(function (item, i) {
                return i + ')' + item;
            }).join('\n');
            res.setHeader('Content-Length', Buffer.byteLength(body));
            res.setHeader('Content-type', 'text/plain;charset="utf-8"');
            res.end(body);
        case 'DELETE':
            // parse parsename 获取"localhost:3000/1?api-key=footbar"中的"1"
            var path = url.parse(req.url).pathname;
            var i = parseInt(path.slice(1), 10);

            //判断是否是数字
            if (isNaN(i)) {
                res.statusCode = 400;
                res.end('Invalid item id');
                // 判断元素是否存在
            } else if (!items[i]) {
                res.statusCode = 404;
                res.end('Item not found');
            } else {
                // splice 删除指定元素,并改变原有数组
                items.splice(i, 1);
                res.end('OK\n');
            }
    }
});

server.listen(3000);

Node 对url的解析提供了.parse()函数。

require('url').parse('http://localhost:3000/1?api-key=footbar')

URL{
  protocol: 'http:',
  slashes: true,
  auth: null,
  host: 'localhost:3000',
  port: '3000',
  hostname: 'localhost',
  hash: null,
  search: '?api-key=footbar',
  query: 'api-key=footbar',
  pathname: '/1',
  path: '/1?api-key=footbar',
  href: 'http://localhost:3000/1?api-key=footbar'
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容