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()
}
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.
An event loop- it is a javascript runtime environment that processes the requests in a loop.