Created
March 25, 2013 08:49
-
-
Save sivagao/5235767 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var http = require('http'), | |
| url = require('url'); | |
| var todos = [{ | |
| id: 1, | |
| title: 'aa', | |
| done: false | |
| }, { | |
| id: 2, | |
| title: 'bb', | |
| done: true | |
| }, { | |
| id: 3, | |
| title: 'cc', | |
| done: false | |
| }], | |
| server = http.createServer(); | |
| var idRe = new RegExp('^/api/todo/([0-9]+)[^0-9]*$'), | |
| searchRe = new RegExp('^/api/todo/search.*$'); | |
| /* | |
| extract POST data in node.js - | |
| var qs = require('querystring'); | |
| function (request, response) { | |
| if (request.method == 'POST') { | |
| var body = ''; | |
| request.on('data', function (data) { | |
| body += data; | |
| }); | |
| request.on('end', function () { | |
| var POST = qs.parse(body); | |
| // use POST | |
| }); | |
| } | |
| } | |
| */ | |
| /* | |
| using express framework! | |
| app.post('/', function(request, response){ | |
| console.log(request.body.user.name); | |
| console.log(request.body.user.email); | |
| }); | |
| */ | |
| server.on('request', function(req, res) { | |
| res.setHeader('content-type', 'application/json'); | |
| if (idRe.test(req.url)) { | |
| var parts = idRe.exec(req.url); | |
| // return the ID | |
| if (todos[parts[1]]) { | |
| res.end(JSON.stringify(todos[parts[1]])); | |
| } | |
| } else if (searchRe.test(req.url)) { | |
| var data = ''; | |
| req.on('data', function(part) { | |
| data += part; | |
| }); | |
| req.on('end', function() { | |
| var search = JSON.parse(data); | |
| // search the todos array by key - value pair | |
| res.end(JSON.stringify( | |
| todos.filter(function(item) { | |
| return Object.keys(search).every(function(key) { | |
| return item[key] && item[key] == search[key]; | |
| }); | |
| }))); | |
| }); | |
| } else { | |
| console.log('Unknown', req.url); | |
| res.end(); | |
| } | |
| }); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment