构建 RESTful Web 服务

通过req.method,判断请求类型,然后进行对应的操作。通过req.setEncoding('utf-8')把二进制数据换成人看的数据。Buffer.byteLength是字节长度,

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('end', function () {
                items.push('item')
                res.end('OK')
            })
            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)
            break;
        case 'DELETE':
            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{
                item.slice(i, 1)
                res.end('OK')
            }
            break;
    }
})
server.listen(3000)

随机浏览