You are on page 1of 32

Desarrollo de Aplicaciones

Web
Daniel Sánchez Ruiz
Unidad Profesional Interdisciplinaria de Ingeniería campus Tlaxcala
Leaving movie reviews
Besides searching movies, users can leave reviews for them. So let’s
create the routes to post, put and delete reviews. post is for creating a
review, put is for editing a review, and delete for deleting reviews.
Leaving movie reviews
We then add a route ‘/review’ which handles post, put and delete http
requests all within this one route call.
That is to say, if the ‘/review’ route receives a post http request to add a
review, we call apiPostReview.
If ‘ /review ’ receives a put http request to edit a review, call
apiUpdateReview.
And finally, if ‘ /review ’ receives a delete http request to delete a
review, call apiDeleteReview.
Leaving movie reviews
Leaving movie reviews
We get information from the request ’ s body parameter. Previously in
MoviesController, we got information from the request ’ s query
parameter as we extracted data from the URL e.g. req.query.title. This
time, we retrieve the data from the body of the request.
In the Vue frontend of the app, we call this endpoint with something
like: this._http.post<any>("http://localhost:5000/api/v1/movies/review",
data)
Leaving movie reviews
Leaving movie reviews
We then call ReviewsDAO.updateReview and pass in user_id to ensure that the user
who is updating the view is the one who has created it.

if (ReviewResponse.modifiedCount === 0) {
throw new Error('unable to update review. User may not be original poster');
}
updateReview returns a document ReviewResponse which contains the property
modifiedCount. modifiedCount contains the number of modified documents. We
check modifiedCount to ensure that it is not zero. If it is, it means the review has not
been updated and we throw an error.
Leaving movie reviews
Leaving movie reviews
Leaving movie reviews
We import mongodb to get access to ObjectId. We need ObjectId to
convert an id string to a MongoDB Object id later on.
The rest of the code, notice that it is similar to MoviesDAO. If
ReviewsDAO.reviews is not filled, we then access the database reviews
collection. Note that if the reviews collection doesn ’ t yet exist in the
database, MongoDB automatically creates it for us.
Design patterns
MVC (Model-View-Controller) is a pattern in software design
commonly used to implement user interfaces, data, and controlling
logic. It emphasizes a separation between the software's business logic
and display.
This "separation of concerns" provides for a better division of labor and
improved maintenance. Some other design patterns are based on MVC,
such as MVVM (Model-View-Viewmodel), MVP (Model-View-
Presenter), and MVW (Model-View-Whatever).
Design patterns
The three parts of the MVC software-design pattern can be described as
follows:

• Model: Manages data and business logic.


• View: Handles layout and display.
• Controller: Routes commands to the model and view parts.

Imagine a simple shopping list app. All we want is a list of the name, quantity
and price of each item we need to buy this week.
Design patterns
Design patterns
The Model
The model defines what data the app should contain. If the state of this
data changes, then the model will usually notify the view (so the display
can change as needed) and sometimes the controller (if different logic is
needed to control the updated view).
Going back to our shopping list app, the model would specify what data
the list items should contain — item, price, etc. — and what list items
are already present.
Design patterns
The View

The view defines how the app's data should be displayed.


In our shopping list app, the view would define how the list is presented
to the user, and receive the data to display from the model.
Design patterns
The Controller
The controller contains logic that updates the model and/or view in response to input
from the users of the app.
So for example, our shopping list could have input forms and buttons that allow us to
add or delete items. These actions require the model to be updated, so the input is
sent to the controller, which then manipulates the model as appropriate, which then
sends updated data to the view.
You might however also want to just update the view to display the data in a different
format, e.g., change the item order to alphabetical, or lowest to highest price. In this
case the controller could handle this directly without needing to update the model.
Introduction to HTTP
Let's say someone wants to visit your web page. They type in its URL or
click a link to your site from a page they are already on. Their web
browser creates an HTTP request, which is sent to the server hosting
your website.
Once a web server receives the HTTP request from your browser, it can
interpret it and then send back a response. The response that the server
sends might be simple, such as just reading an HTML or image file from
disk and sending it.
Introduction to HTTP
Or, the response might be more complex, maybe using server-side
software to dynamically generate the content before sending it:
Introduction to HTTP
The request is made up of four main parts: the method, path, headers,
and body.
Some types of requests don't have a body. If you just visit a web page,
your browser will not send a body, whereas if you are submitting a form
(for example, by logging into a site or performing a search), then your
request will have a body containing the data you're submitting.
Introduction to HTTP
The first request will be to an example page with the URL
https://www.example.com/page. When your browser visits that page,
behind the scenes, this is what it's sending:
Introduction to HTTP
The first line contains the method (GET) and the path (/page). It also
contains the HTTP version, in this case, 1.1, although you don't have to
worry about this.
Many different HTTP methods can be used, depending on how you
want to interact with the remote page.
Some common ones are GET (retrieve the remote page), POST (send
data to the remote page), PUT (create a remote page), and DELETE
(delete the remote page).
Introduction to HTTP
When writing a web application, the vast majority of the time, you will
only deal with GET requests.
When you start accepting forms, you'll also have to use POST requests.
It is only when you are working with advanced features such as creating
REST APIs that you will have to worry about PUT, DELETE, and other
methods.
Introduction to HTTP
Referring back to the example request again, from line 2 onward are the
headers of the request.
The headers contain extra metadata about the request. Each header is on
its own line, with the header name and its value separated by a colon.
Most are optional (except for Host).
Header names are not case sensitive. For the sake of the example, we're
only showing three common headers here.
Introduction to HTTP
• Host: As mentioned, this is the only header that is required (for HTTP 1.1 or later).
It is needed for the webserver to know which website or application should respond
to the request, in case there are multiple sites hosted on a single server.
• User-Agent: Your browser usually sends to the server a string identifying its version
and operating system. Your server application could use this to serve different pages
to different devices (for example, a mobile-specific page for smartphones).
• Cookie: You have probably seen a message when visiting a web page that lets you
know that it is storing a cookie in the browser. These are small pieces of information
that a website can store in your browser that can be used to identify you or save
settings for when you return to the site. If you were wondering about how your
browser sends these cookies back to the server, it is through this header.
Introduction to HTTP
Now that you've seen requests, we'll take a look at the HTTP responses
that come back from the server.
An HTTP response looks similar to a request and consists of three main
parts: a status, headers, and a body. Like a request, though, depending
on the type of response, it might not have a body.
The first response example is a simple successful response:
Introduction to HTTP
The first line contains the HTTP version, a numeric status code (200), and then a text
description of what the code means. Lines 2 to 5 contain headers, similar to a request.
• Server: This is similar to but the opposite of the User-Agent header: this is the server
telling the client what software it is running.
• Content-Length: The client uses this value to determine how much data to read from the
server to get the body.
• Content-Type: The server uses this header to indicate to the client what type of data it is
sending. The client can then choose how it will display the data—an image must be
displayed differently to HTML, for example.
• Set-Cookie: We saw in the first request example how a client sends a cookie to the server.
This is the corresponding header that a server sends to set that cookie in the browser.
Introduction to HTTP
The various status codes are grouped by the type of success or failure
they indicate:
• 100-199: The server sends codes in this range to indicate protocol
changes or that more data is required. You don't have to worry about
these.
• 200-299: A status code in this range indicates the successful handling
of a response. The most common one you will deal with is 200 OK.
Introduction to HTTP
• 300-399: A status code in this range means the page you are requesting
has moved to another address. An example of this is a URL shortening
service that would redirect you from the short URL to the full one
when you visit it. Common responses are 301 Moved Permanently or
302 Found. When sending a redirect response, the server will also
include a Location header that contains the URL that should be
redirected to.
Introduction to HTTP
• 400-499: A status code in this range means that the request could not
be handled because there was a problem with what the client sent. This
is in contrast to a request not being able to be handled due to a
problem on the server (we will discuss those soon). We've already
seen a 404 Not Found response; this is due to a bad request because
the client is requesting a document that does not exist. Some other
common responses are 401Unauthorized (the client should log in) and
403 Forbidden (the client is not allowed to access the specific
resource). Both problems could be avoided by having the client login,
hence them being considered client-side (request) problems.
Introduction to HTTP
• 500-599: Status codes in this range indicate an error on the server's
side. The client shouldn't expect to be able to adjust the request to fix
the problem. When working with Node, the most common server error
status you will see is 500 Internal Server Error. This will be generated
if your code raises an exception. Another common one is 504 Gateway
Timeout, which might occur if your code is taking too long to run. The
other variants that are common to see are 502 Bad Gateway and 503
Service Unavailable, which generally mean there is a problem with
your application's hosting in some way.
Testing the API
Tarea
• Realizar un mapa mental donde se hable sobre los headers, investiguen
cuáles más existen, pongan un ejemplo de ellos y mencionen sus
valores más comunes.
• Realizar el mismo ejercicio, pero en esta ocasión para los códigos de
respuesta, cuáles más existen a los que se mencionaron, mencionen
brevemente cuándo se ocupan.

You might also like