Skip to content

Instantly share code, notes, and snippets.

@francylang
Created November 27, 2017 01:36
Show Gist options
  • Save francylang/0a26460375ad3f50937aa6c1aee3c59e to your computer and use it in GitHub Desktop.
Save francylang/0a26460375ad3f50937aa6c1aee3c59e 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': 'francy lang', 'message': 'hi there!' },
  { 'id': 2, 'user': 'joe lang', '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 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, {
    'Content-Type': 'application/json'
  });
  response.write(JSON.stringify(messages));
  response.end();
}

const addMessage = (newMessage, response) => {
  messages.push(newMessage);
  response.writeHead(201, {
    'Content-Type': 'application/json'
  });
  response.write(JSON.stringify(messages));
  response.end()
}

Checks for Understanding

1. What type of information is included in the header of a request?

  • Conditional requests. Request header contain more information about the resource to be fetched or about the client itself.

2. What are the major RESTful methods and what do each of them do?

  • GET - Retrieves the resource information sent by the request.
  • POST - Creates a new resource.
  • PUT - Update an entire resource.
  • PATCH - Updates a portion of a resource.
  • DELETE - Destroy an entire specific resource by the request.

3. What is Node?

  • An event loop- it is a javascript runtime environment that processes the requests in a loop.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment