Skip to content

Instantly share code, notes, and snippets.

@dsdunn
Created August 11, 2018 03:09
Show Gist options
  • Select an option

  • Save dsdunn/9f9c98f33f8976fd1c6e5aaac764b2b6 to your computer and use it in GitHub Desktop.

Select an option

Save dsdunn/9f9c98f33f8976fd1c6e5aaac764b2b6 to your computer and use it in GitHub Desktop.
const http = require('http');
const url = require('url');
const server = http.createServer();
let messages = [
{ 'id': 1, 'user': 'Cardi B', 'message': 'I got money!'},
{ 'id': 2, 'user': 'the Munchkins', 'message': 'ding dong the witch is dead'},
{ 'id': 3, 'user': 'bart simpson', 'message': 'don\'t have a cow, man'}
];
server.listen(3000, () => {
console.log('The HTTP server is listening at 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) => {
newMessage = Object.assign(newMessage, JSON.parse(data));
});
request.on('end', () => {
addMessage(newMessage, response);
})
}
});
const getAllMessages = (response) => {
response.writeHead(200, { 'ContentType': 'text/plain' });
response.write(JSON.stringify(messages));
response.end();
}
const addMessage = (newMessage, response) => {
messages.push(newMessage);
response.writeHead(201, { 'ContentType': 'text/plain' });
response.write(JSON.stringify(messages));
response.end();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment