Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions src/content/3/en/part3a.md
Original file line number Diff line number Diff line change
Expand Up @@ -318,9 +318,9 @@ app.get('/', (request, response) => {
})
```

The event handler function accepts two parameters. The first [request](http://expressjs.com/en/4x/api.html#req) parameter contains all of the information of the HTTP request, and the second [response](http://expressjs.com/en/4x/api.html#res) parameter is used to define how the request is responded to.
The event handler function accepts two parameters. The first [request](https://expressjs.com/en/5x/api/request/) parameter contains all of the information of the HTTP request, and the second [response](https://expressjs.com/en/5x/api/response/) parameter is used to define how the request is responded to.

In our code, the request is answered by using the [send](http://expressjs.com/en/4x/api.html#res.send) method of the _response_ object. Calling the method makes the server respond to the HTTP request by sending a response containing the string <code>\<h1>Hello World!\</h1></code> that was passed to the _send_ method. Since the parameter is a string, Express automatically sets the value of the <i>Content-Type</i> header to be <i>text/html</i>. The status code of the response defaults to 200.
In our code, the request is answered by using the [send](https://expressjs.com/en/5x/api/response/#ressendbody) method of the _response_ object. Calling the method makes the server respond to the HTTP request by sending a response containing the string <code>\<h1>Hello World!\</h1></code> that was passed to the _send_ method. Since the parameter is a string, Express automatically sets the value of the <i>Content-Type</i> header to be <i>text/html</i>. The status code of the response defaults to 200.

We can verify this from the <i>Network</i> tab in developer tools:

Expand All @@ -334,7 +334,7 @@ app.get('/api/notes', (request, response) => {
})
```

The request is responded to with the [json](http://expressjs.com/en/4x/api.html#res.json) method of the _response_ object. Calling the method will send the __notes__ array that was passed to it as a JSON formatted string. Express automatically sets the <i>Content-Type</i> header with the appropriate value of <i>application/json</i>.
The request is responded to with the [json](https://expressjs.com/en/5x/api/response/#resjsonbody) method of the _response_ object. Calling the method will send the __notes__ array that was passed to it as a JSON formatted string. Express automatically sets the <i>Content-Type</i> header with the appropriate value of <i>application/json</i>.

![api/notes gives the formatted JSON data again](../../images/3/6new.png)

Expand Down Expand Up @@ -428,11 +428,11 @@ In some places (see e.g. [Richardson, Ruby: RESTful Web Services](http://shop.or

### Fetching a single resource

Let's expand our application so that it offers a REST interface for operating on individual notes. First, let's create a [route](http://expressjs.com/en/guide/routing.html) for fetching a single resource.
Let's expand our application so that it offers a REST interface for operating on individual notes. First, let's create a [route](https://expressjs.com/en/5x/guide/routing/) for fetching a single resource.

The unique address we will use for an individual note is of the form <i>notes/10</i>, where the number at the end refers to the note's unique id number.

We can define [parameters](http://expressjs.com/en/guide/routing.html#route-parameters) for routes in Express by using the colon syntax:
We can define [parameters](https://expressjs.com/en/5x/guide/routing/#route-parameters) for routes in Express by using the colon syntax:

```js
app.get('/api/notes/:id', (request, response) => {
Expand All @@ -444,7 +444,7 @@ app.get('/api/notes/:id', (request, response) => {

Now <code>app.get('/api/notes/:id', ...)</code> will handle all HTTP GET requests that are of the form <i>/api/notes/SOMETHING</i>, where <i>SOMETHING</i> is an arbitrary string.

The <i>id</i> parameter in the route of a request can be accessed through the [request](http://expressjs.com/en/api.html#req) object:
The <i>id</i> parameter in the route of a request can be accessed through the [request](https://expressjs.com/en/5x/api/request/) object:

```js
const id = request.params.id
Expand Down Expand Up @@ -484,7 +484,7 @@ app.get('/api/notes/:id', (request, response) => {
})
```

Since no data is attached to the response, we use the [status](http://expressjs.com/en/4x/api.html#res.status) method for setting the status and the [end](http://expressjs.com/en/4x/api.html#res.end) method for responding to the request without sending any data.
Since no data is attached to the response, we use the [status](https://expressjs.com/en/5x/api/response/#resstatuscode) method for setting the status and the [end](https://expressjs.com/en/5x/api/response/#resenddata-encoding-callback) method for responding to the request without sending any data.

The if-condition leverages the fact that all JavaScript objects are [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), meaning that they evaluate to true in a comparison operation. However, _undefined_ is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) meaning that it will evaluate to false.

Expand Down Expand Up @@ -549,7 +549,7 @@ If you use *IntelliJ WebStorm* instead, you can use a similar procedure with its

Next, let's make it possible to add new notes to the server. Adding a note happens by making an HTTP POST request to the address <http://localhost:3001/api/notes>, and by sending all the information for the new note in the request [body](https://www.rfc-editor.org/rfc/rfc9112#name-message-body) in JSON format.

To access the data easily, we need the help of the Express [json-parser](https://expressjs.com/en/api.html) that we can use with the command _app.use(express.json())_.
To access the data easily, we need the help of the Express [json-parser](https://expressjs.com/en/5x/api/express/#expressjsonoptions) that we can use with the command _app.use(express.json())_.

Let's activate the json-parser and implement an initial handler for dealing with the HTTP POST requests:

Expand Down Expand Up @@ -630,7 +630,7 @@ Postman also allows users to save requests, but the situation can get quite chao

> **Important sidenote**
>
> Sometimes when you're debugging, you may want to find out what headers have been set in the HTTP request. One way of accomplishing this is through the [get](http://expressjs.com/en/4x/api.html#req.get) method of the _request_ object, that can be used for getting the value of a single header. The _request_ object also has the <i>headers</i> property, that contains all of the headers of a specific request.
> Sometimes when you're debugging, you may want to find out what headers have been set in the HTTP request. One way of accomplishing this is through the [get](https://expressjs.com/en/5x/api/request/#reqgetfield) method of the _request_ object, that can be used for getting the value of a single header. The _request_ object also has the <i>headers</i> property, that contains all of the headers of a specific request.
>
> Problems can occur with the VS REST client if you accidentally add an empty line between the top row and the row specifying the HTTP headers. In this situation, the REST client interprets this to mean that all headers are left empty, which leads to the backend server not knowing that the data it has received is in the JSON format.
>
Expand Down Expand Up @@ -861,7 +861,7 @@ POST is the only HTTP request type that is neither <i>safe</i> nor <i>idempotent

### Middleware

The Express [json-parser](https://expressjs.com/en/api.html) used earlier is a [middleware](http://expressjs.com/en/guide/using-middleware.html).
The Express [json-parser](https://expressjs.com/en/5x/api/express/#expressjsonoptions) used earlier is a [middleware](https://expressjs.com/en/resources/middleware/body-parser/).

Middleware are functions that can be used for handling _request_ and _response_ objects.

Expand Down
20 changes: 10 additions & 10 deletions src/content/3/es/part3a.md
Original file line number Diff line number Diff line change
Expand Up @@ -318,9 +318,9 @@ app.get('/', (request, response) => {
})
```

La función del controlador de eventos acepta dos parámetros. El primer parámetro [request](http://expressjs.com/en/4x/api.html#req) contiene toda la información de la solicitud HTTP y el segundo parámetro [response](http://expressjs.com/en/4x/api.html#res) se utiliza para definir cómo se responde a la solicitud.
La función del controlador de eventos acepta dos parámetros. El primer parámetro [request](https://expressjs.com/en/5x/api/request/) contiene toda la información de la solicitud HTTP y el segundo parámetro [response](https://expressjs.com/en/5x/api/response/) se utiliza para definir cómo se responde a la solicitud.

En nuestro código, la solicitud se responde utilizando el método [send](http://expressjs.com/en/4x/api.html#res.send) del objeto _response_. Llamar al método hace que el servidor responda a la solicitud HTTP enviando una respuesta que contiene el string <code>\<h1>Hello World!\</h1></code>, que se pasó al método _send_. Dado que el parámetro es un string, Express establece automáticamente el valor de la cabecera <i>Content-Type</i> en <i>text/html</i>. El código de estado de la respuesta predeterminado es 200.
En nuestro código, la solicitud se responde utilizando el método [send](https://expressjs.com/en/5x/api/response/#ressendbody) del objeto _response_. Llamar al método hace que el servidor responda a la solicitud HTTP enviando una respuesta que contiene el string <code>\<h1>Hello World!\</h1></code>, que se pasó al método _send_. Dado que el parámetro es un string, Express establece automáticamente el valor de la cabecera <i>Content-Type</i> en <i>text/html</i>. El código de estado de la respuesta predeterminado es 200.

Podemos verificar esto desde la pestaña <i>Network</i> en las herramientas para desarrolladores:

Expand All @@ -334,7 +334,7 @@ app.get('/api/notes', (request, response) => {
})
```

La solicitud se responde con el método [json](http://expressjs.com/en/4x/api.html#res.json) del objeto _response_. Llamar al método enviará el array __notes__ que se le pasó como un string con formato JSON. Express establece automáticamente la cabecera <i>Content-Type</i> con el valor apropiado de <i>application/json</i>.
La solicitud se responde con el método [json](https://expressjs.com/en/5x/api/response/#resjsonbody) del objeto _response_. Llamar al método enviará el array __notes__ que se le pasó como un string con formato JSON. Express establece automáticamente la cabecera <i>Content-Type</i> con el valor apropiado de <i>application/json</i>.

![api/notes devuelve los datos en formato JSON otra vez](../../images/3/6new.png)

Expand Down Expand Up @@ -460,11 +460,11 @@ En algunos lugares (ver por ejemplo, [Richardson, Ruby: RESTful Web Services](ht

### Obteniendo un solo recurso

Ampliemos nuestra aplicación para que ofrezca una interfaz REST para operar con notas individuales. Primero, creemos una [ruta](http://expressjs.com/en/guide/routing.html) para buscar un solo recurso.
Ampliemos nuestra aplicación para que ofrezca una interfaz REST para operar con notas individuales. Primero, creemos una [ruta](https://expressjs.com/en/5x/guide/routing/) para buscar un solo recurso.

La dirección única que usaremos para una nota individual es de la forma <i>notes/10</i>, donde el número al final se refiere al número de id único de la nota.

Podemos definir [parámetros](http://expressjs.com/en/guide/routing.html#route-parameters) para rutas en Express usando la sintaxis de dos puntos:
Podemos definir [parámetros](https://expressjs.com/en/5x/guide/routing/#route-parameters) para rutas en Express usando la sintaxis de dos puntos:

```js
app.get('/api/notes/:id', (request, response) => {
Expand All @@ -476,7 +476,7 @@ app.get('/api/notes/:id', (request, response) => {

Ahora <code>app.get('/api/notes/:id', ...)</code> manejará todas las solicitudes HTTP GET, que tienen el formato <i>/api/notes/SOMETHING</i>, donde <i>SOMETHING</i> es una cadena arbitraria.

Se puede acceder al parámetro <i>id</i> en la ruta de una solicitud a través del objeto [request](http://expressjs.com/en/api.html#req):
Se puede acceder al parámetro <i>id</i> en la ruta de una solicitud a través del objeto [request](https://expressjs.com/en/5x/api/request/):

```js
const id = request.params.id
Expand Down Expand Up @@ -569,7 +569,7 @@ app.get('/api/notes/:id', (request, response) => {
})
```

Dado que no se adjuntan datos a la respuesta, utilizamos el método [status](http://expressjs.com/en/4x/api.html#res.status) para establecer el estado y el método [end](http://expressjs.com/en/4x/api.html#res.end) para responder a la solicitud sin enviar ningún dato.
Dado que no se adjuntan datos a la respuesta, utilizamos el método [status](https://expressjs.com/en/5x/api/response/#resstatuscode) para establecer el estado y el método [end](https://expressjs.com/en/5x/api/response/#resenddata-encoding-callback) para responder a la solicitud sin enviar ningún dato.

La condición if aprovecha el hecho de que todos los objetos JavaScript son [truthy](https://developer.mozilla.org/es/docs/Glossary/Truthy), lo que significa que se evalúan como verdaderos en una operación de comparación. Sin embargo, _undefined_ es [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy), lo que significa que se evaluará como falso.

Expand Down Expand Up @@ -634,7 +634,7 @@ Si usas *IntelliJ WebStorm* en cambio, puedes usar un procedimiento similar con

A continuación, hagamos posible agregar nuevas notas al servidor. La adición de una nota ocurre al hacer una solicitud HTTP POST a la dirección <http://localhost:3001/api/notes>, y al enviar toda la información de la nueva nota en el [body](https://www.rfc-editor.org/rfc/rfc9112#name-message-body) de la solicitud en formato JSON.

Para acceder a los datos fácilmente, necesitamos la ayuda del [json-parser](https://expressjs.com/en/api.html) de Express, que se usa con el comando _app.use(express.json())_.
Para acceder a los datos fácilmente, necesitamos la ayuda del [json-parser](https://expressjs.com/en/5x/api/express/#expressjsonoptions) de Express, que se usa con el comando _app.use(express.json())_.

Activemos json-parser e implementemos un controlador inicial para manejar las solicitudes HTTP POST:

Expand Down Expand Up @@ -715,7 +715,7 @@ Postman también permite a los usuarios guardar solicitudes, pero la situación

> **Nota al margen importante**
>
> A veces, cuando estas depurando, es posible que desees averiguar qué cabeceras se han configurado en la solicitud HTTP. Una forma de lograr esto es mediante el método [get](http://expressjs.com/en/4x/api.html#req.get) del objeto _request_, que se puede usar para obtener el valor de una sola cabecera. El objeto _request_ también tiene la propiedad <i>headers (cabeceras)</i>, que contiene todas los cabeceras de una solicitud específica.
> A veces, cuando estas depurando, es posible que desees averiguar qué cabeceras se han configurado en la solicitud HTTP. Una forma de lograr esto es mediante el método [get](https://expressjs.com/en/5x/api/request/#reqgetfield) del objeto _request_, que se puede usar para obtener el valor de una sola cabecera. El objeto _request_ también tiene la propiedad <i>headers (cabeceras)</i>, que contiene todas los cabeceras de una solicitud específica.
>
> Pueden ocurrir problemas con el cliente VS REST si agrega accidentalmente una línea vacía entre la fila superior y la fila que especifica los cabeceras HTTP. En esta situación, el cliente REST interpreta que esto significa que todos los cabeceras se dejan vacíos, lo que hace que el servidor backend no sepa que los datos que ha recibido están en formato JSON.
>
Expand Down Expand Up @@ -950,7 +950,7 @@ POST es el único tipo de solicitud HTTP que no es ni <i>seguro</i> ni <i>idempo

### Middleware

El [json-parser](https://expressjs.com/en/api.html) de Express que utilizamos anteriormente es un [middleware](https://expressjs.com/es/guide/using-middleware.html).
El [json-parser](https://expressjs.com/en/5x/api/express/#expressjsonoptions) de Express que utilizamos anteriormente es un [middleware](https://expressjs.com/en/resources/middleware/body-parser/).

Los middleware son funciones que se pueden utilizar para manejar objetos de _request_ y _response_.

Expand Down
Loading