'use strict' const http = require('http') const server = http.createServer((req, res) => { if (req.method === 'GET') { res.setHeader('Content-Type', 'text/html') if (req.url === '/') return res.end(html()) res.setHeader('Content-Type', 'application/json') if (req.url === '/friends') return res.end(friends()) return } if (req.method === 'POST') { if (req.url === '/') return action(req, res) } }) function html (res) { return `
` } function friends () { return JSON.stringify(friends.list) } friends.list = [Buffer('Dave').toString('base64')] friends.add = (friend) => friends.list.push(Buffer(friend).toString('base64')) function action (req, res) { var data = '' req.on('data', (chunk) => data += chunk) req.on('end', () => { try { data = JSON.parse(data) } catch (e) { res.end('{"ok": false}') return } if (data.cmd === 'add') { friends.add(data.friend) } res.end('{"ok": true}') }) } server.listen(3000)