You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
const http = require('http');
const url = require('url');
const server = http.createServer();
let messages = [
{ 'id': 1, 'user': 'Jason Hughes', '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 at Port 3000.');
});
server.on('request', (request, response) => {
if (request.method === 'GET') {
getAllMessages(response);
}
else if (request.method === 'POST') {
let newMessage = { 'id': new Date(),
'user': 'alex trebek',
'message': 'answer in the form of a question'
};
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?
Information that defines the operating parameters of an HTTP transaction.
Examples of HTTP header information includes:
RESTful method
HTTP version
User Agent
Content-Types
Acceptable encoding, language, charset, etc.
2. What are the major RESTful methods and what do each of them do?
GET - Retrieves the resource info sent by the request.
POST - Creates a new resource.
PUT - Update an entire resource.
PATCH - Updates only portion of a resource.
DELETE - Delete an entire specific resource by the request.
3. What is Node?
Node is an open-source server framework that allows us to apply JS skills outside of the browser. It was built to make asynchronous I/O easier. It is an event-driven and non-blocking model.