Created
April 26, 2018 19:17
-
-
Save stevenleelawson/f7c33e6bd3b15d4a4f867dcfa0af687b to your computer and use it in GitHub Desktop.
node tutorial
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
const http = require("http"); | |
const url = require('url'); | |
const server = http.createServer(); | |
let messages = [ | |
{"id": 1, | |
"user": "brittany storoz", | |
"message": "hi there!" | |
}, | |
{"id": 2, | |
"user": "bob loblaw", | |
"message": "check out my law blog" | |
}, | |
{"id": 3, | |
"user": "lorem ipsum", | |
"message": "dolor set amet" | |
} | |
]; | |
server.listen(3000, () => { | |
console.log('The HTTP server is listening on Port 3000'); | |
}); | |
server.on('request', (request, response) => { | |
if (request.method === 'GET') { | |
getAllMessages(response) | |
} else if (request.method === 'POST') { | |
let newMessage = { 'id': new Date() }; | |
request.on('data', (data) => { | |
messages.push(JSON.parse(data)) | |
newMessage = Object.assign(newMessage, JSON.parse(data)); | |
}); | |
request.on('end', () => { | |
addMessage(newMessage, response); | |
}) | |
} | |
}); | |
const getAllMessages = (response) => { | |
response.writeHead(200, { "Content-Type": "application/json" }); | |
response.write(JSON.stringify(messages)); | |
response.end(); | |
} | |
const addMessage = (newMessage, response) => { | |
response.writeHead(201, {"Content-Type": "application/json"}) | |
response.write(JSON.stringify(newMessage)); | |
response.end(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment