Created
August 12, 2018 22:27
-
-
Save jeremiahjstanley/e582019634adaa5ccc1d33da6115ee9c to your computer and use it in GitHub Desktop.
Node Server 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': 'user 1', 'message': 'generic message' }, | |
{ 'id': 2, 'user': 'user 2', 'message': 'another generic message' }, | |
{ 'id': 3, 'user': 'user 3', 'message': 'and a third!' } | |
]; | |
addMessage = (newMessage, response) => { | |
response.writeHead(201, { 'Content-Type': 'text/plain' }); | |
response.write(JSON.stringify(newMessage)); | |
response.end(JSON.stringify(newMessage)); | |
}; | |
getAllMessages = response => { | |
response.writeHead(200, { 'Content-Type': 'application/json' }); | |
response.end(JSON.stringify(messages)); | |
}; | |
server.listen(3000, () => { | |
console.log('The HTTP server is listening at Port 3000.'); | |
}); | |
server.on('request', (request, response) => { | |
response.writeHead(200, { 'Content-Type': 'text/plain' }); | |
response.write('Hello World\n'); | |
response.end(); | |
}); | |
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); | |
}); | |
} | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment