chore(i18n,curriculum): update translations

This commit is contained in:
camperbot
2021-10-27 15:10:57 +00:00
committed by Mrugesh Mohapatra
parent e139fbcf13
commit c1fb339bbc
539 changed files with 3319 additions and 3352 deletions

View File

@ -1,6 +1,6 @@
---
id: 587d7fb1367417b2b2512bf4
title: Chain Middleware to Create a Time Server
title: Encadenando Middlewares para crear un servidor horario
challengeType: 2
forumTopicId: 301510
dashedName: chain-middleware-to-create-a-time-server
@ -8,9 +8,9 @@ dashedName: chain-middleware-to-create-a-time-server
# --description--
Middleware can be mounted at a specific route using `app.METHOD(path, middlewareFunction)`. Middleware can also be chained inside route definition.
Un middleware se puede montar en una ruta especifica usando `app.METHOD(path, middlewareFunction)`. El middleware también se puede encadenar dentro de la definición de la ruta.
Look at the following example:
Veamos el siguiente ejemplo:
```js
app.get('/user', function(req, res, next) {
@ -21,17 +21,17 @@ app.get('/user', function(req, res, next) {
});
```
This approach is useful to split the server operations into smaller units. That leads to a better app structure, and the possibility to reuse code in different places. This approach can also be used to perform some validation on the data. At each point of the middleware stack you can block the execution of the current chain and pass control to functions specifically designed to handle errors. Or you can pass control to the next matching route, to handle special cases. We will see how in the advanced Express section.
Este método es útil para dividir las operaciones del servidor en unidades más pequeñas. Lo que lleva a una mejor estructura de nuestra aplicación y a la posibilidad de reutilizar código en diferentes lugares. Este método también se puede utilizar para realizar ciertas validaciones de los datos. En cada punto de la pila del middleware puedes bloquear la ejecución de la cadena actual y darle el control a funciones diseñadas específicamente para el manejo de errores. O puedes pasar el control a la siguiente ruta que concuerde, para manejar casos especiales. Veremos cómo en la sección avanzada de Express.
# --instructions--
In the route `app.get('/now', ...)` chain a middleware function and the final handler. In the middleware function you should add the current time to the request object in the `req.time` key. You can use `new Date().toString()`. In the handler, respond with a JSON object, taking the structure `{time: req.time}`.
En la ruta `app.get('/now', ...)` encadena una función del middleware con el controlador final. En la función del middleware debes añadir la hora actual al objeto de petición en la clave `req.time`. Puedes utilizar `new Date().toString()`. En el controlador, responde con un objeto JSON, tomando la estructura `{time: req.time}`.
**Note:** The test will not pass if you dont chain the middleware. If you mount the function somewhere else, the test will fail, even if the output result is correct.
**Nota:** La prueba no pasará si no encadenas el middleware. Si montas la función en otro lugar, la prueba fallará, incluso si el resultado de salida es correcto.
# --hints--
The /now endpoint should have mounted middleware
El endpoint /now debe tener el middleware montado
```js
(getUserInput) =>
@ -49,7 +49,7 @@ The /now endpoint should have mounted middleware
);
```
The /now endpoint should return a time that is +/- 20 secs from now
El endpoint /now debe devolver un tiempo que es +/- 20 segundos a partir de este momento
```js
(getUserInput) =>

View File

@ -1,6 +1,6 @@
---
id: 587d7fb2367417b2b2512bf8
title: Get Data from POST Requests
title: Obtén datos de las peticiones POST
challengeType: 2
forumTopicId: 301511
dashedName: get-data-from-post-requests
@ -8,27 +8,27 @@ dashedName: get-data-from-post-requests
# --description--
Mount a POST handler at the path `/name`. Its the same path as before. We have prepared a form in the html frontpage. It will submit the same data of exercise 10 (Query string). If the body-parser is configured correctly, you should find the parameters in the object `req.body`. Have a look at the usual library example:
Monta un manejador POST en la ruta `/name`. Es la misma ruta de antes. Hemos preparado un formulario en la página principal html. Se enviarán los mismos datos del ejercicio 10 (Query string). Si el "body-parser" está configurado correctamente, debe encontrar los parámetros en el objeto `req.body`. Echa un vistazo al ejemplo de la biblioteca:
<blockquote>route: POST '/library'<br>urlencoded_body: userId=546&#x26;bookId=6754 <br>req.body: {userId: '546', bookId: '6754'}</blockquote>
Respond with the same JSON object as before: `{name: 'firstname lastname'}`. Test if your endpoint works using the html form we provided in the app frontpage.
Responde con el mismo objeto JSON que antes: `{name: 'firstname lastname'}`. Prueba si tu endpoint funciona usando el formulario html que proporcionamos en la página principal de la aplicación.
Tip: There are several other http methods other than GET and POST. And by convention there is a correspondence between the http verb, and the operation you are going to execute on the server. The conventional mapping is:
Nota: Hay varios métodos de http diferentes a GET y POST. Y por convención hay una correspondencia entre el verbo http y la operación que se va a ejecutar en el servidor. La asignación convencional es:
POST (sometimes PUT) - Create a new resource using the information sent with the request,
POST (a veces PUT): Crea un nuevo recurso usando la información enviada con la solicitud,
GET - Read an existing resource without modifying it,
GET: Lee un recurso existente sin modificarlo,
PUT or PATCH (sometimes POST) - Update a resource using the data sent,
PUT o PATCH (a veces POST): Actualiza un recurso usando los datos enviados,
DELETE => Delete a resource.
DELETE => Elimina un recurso.
There are also a couple of other methods which are used to negotiate a connection with the server. Except from GET, all the other methods listed above can have a payload (i.e. the data into the request body). The body-parser middleware works with these methods as well.
También hay un par de otros métodos que se utilizan para negociar una conexión con el servidor. A excepción de GET, todos los demás métodos mencionados anteriormente pueden tener un payload (es decir, los datos en el cuerpo de la solicitud). El middleware body-parser también funciona con estos métodos.
# --hints--
Test 1 : Your API endpoint should respond with the correct name
Prueba 1: El endpoint de tu API debe responder con el nombre correcto
```js
(getUserInput) =>
@ -46,7 +46,7 @@ Test 1 : Your API endpoint should respond with the correct name
);
```
Test 2 : Your API endpoint should respond with the correct name
Prueba 2: El endpoint de tu API debe responder con el nombre correcto
```js
(getUserInput) =>

View File

@ -1,6 +1,6 @@
---
id: 587d7fb2367417b2b2512bf6
title: Get Query Parameter Input from the Client
title: Obtén la entrada de parámetros de consulta del cliente
challengeType: 2
forumTopicId: 301512
dashedName: get-query-parameter-input-from-the-client
@ -8,19 +8,19 @@ dashedName: get-query-parameter-input-from-the-client
# --description--
Another common way to get input from the client is by encoding the data after the route path, using a query string. The query string is delimited by a question mark (?), and includes field=value couples. Each couple is separated by an ampersand (&). Express can parse the data from the query string, and populate the object `req.query`. Some characters, like the percent (%), cannot be in URLs and have to be encoded in a different format before you can send them. If you use the API from JavaScript, you can use specific methods to encode/decode these characters.
Otra forma común de obtener la entrada del cliente es codificando los datos después de la ruta, usando una cadena de consulta. La cadena de consulta está delimitada por un signo de interrogación (?), e incluye parejas de campo=valor. Cada pareja está separada por un ampersand (&). Express puede analizar los datos de la cadena de consulta, y llenar el objeto `req.query`. Algunos caracteres, como el porcentaje (%), no pueden estar en URLs y tienen que ser codificados en un formato diferente antes de poder enviarlos. Si usas la API desde JavaScript, puedes usar métodos específicos para codificar/decodificar estos caracteres.
<blockquote>route_path: '/library'<br>actual_request_URL: '/library?userId=546&#x26;bookId=6754' <br>req.query: {userId: '546', bookId: '6754'}</blockquote>
# --instructions--
Build an API endpoint, mounted at `GET /name`. Respond with a JSON document, taking the structure `{ name: 'firstname lastname'}`. The first and last name parameters should be encoded in a query string e.g. `?first=firstname&last=lastname`.
Construye un endpoint para el API, montado en `GET /name`. Responde con un documento JSON, tomando la estructura `{ name: 'firstname lastname'}`. Los parámetros del nombre y apellido deben codificarse en una cadena de consulta, por ejemplo, `?first=firstname&last=lastname`.
**Note:** In the following exercise you are going to receive data from a POST request, at the same `/name` route path. If you want, you can use the method `app.route(path).get(handler).post(handler)`. This syntax allows you to chain different verb handlers on the same path route. You can save a bit of typing, and have cleaner code.
**Nota:** En el siguiente ejercicio va a recibir datos de una solicitud POST, a la misma ruta `/name`. Si lo deseas, puedes utilizar el método `app.route(path).get(handler).post(handler)`. Esta sintaxis permite encadenar diferentes manejadores de verbos en la misma ruta. Puedes ahorrar un poco de escritura y tener un código más limpio.
# --hints--
Test 1 : Your API endpoint should respond with the correct name
Prueba 1: El endpoint de tu API debe responder con el nombre correcto
```js
(getUserInput) =>
@ -38,7 +38,7 @@ Test 1 : Your API endpoint should respond with the correct name
);
```
Test 2 : Your API endpoint should respond with the correct name
Prueba 2: El endpoint de tu API debe responder con el nombre correcto
```js
(getUserInput) =>

View File

@ -1,6 +1,6 @@
---
id: 587d7fb2367417b2b2512bf5
title: Get Route Parameter Input from the Client
title: Obtén la entrada de parámetros de ruta del cliente
challengeType: 2
forumTopicId: 301513
dashedName: get-route-parameter-input-from-the-client
@ -8,17 +8,17 @@ dashedName: get-route-parameter-input-from-the-client
# --description--
When building an API, we have to allow users to communicate to us what they want to get from our service. For example, if the client is requesting information about a user stored in the database, they need a way to let us know which user they're interested in. One possible way to achieve this result is by using route parameters. Route parameters are named segments of the URL, delimited by slashes (/). Each segment captures the value of the part of the URL which matches its position. The captured values can be found in the `req.params` object.
Cuando construimos una API, tenemos que permitir que los usuarios nos comuniquen lo que quieren obtener de nuestro servicio. Por ejemplo, si el cliente solicita información sobre un usuario almacenado en la base de datos, necesitan una forma de hacernos saber en qué usuario están interesados. Una posible forma de lograr este resultado es utilizando parámetros de ruta. Los parámetros de ruta son segmentos con nombre de la URL, delimitados por barras (/). Cada segmento captura el valor de la parte de la URL que coincide con su posición. Los valores capturados pueden encontrarse en el objeto `req.params`.
<blockquote>route_path: '/user/:userId/book/:bookId'<br>actual_request_URL: '/user/546/book/6754' <br>req.params: {userId: '546', bookId: '6754'}</blockquote>
# --instructions--
Build an echo server, mounted at the route `GET /:word/echo`. Respond with a JSON object, taking the structure `{echo: word}`. You can find the word to be repeated at `req.params.word`. You can test your route from your browser's address bar, visiting some matching routes, e.g. `your-app-rootpath/freecodecamp/echo`.
Construye un servidor de eco, montado en la ruta `GET /:word/echo`. Responde con un documento JSON, tomando la estructura `{echo: word}`. Puedes encontrar la palabra que se repetirá en `req.params.word`. Puedes probar tu ruta desde la barra de direcciones de tu navegador, visitando algunas rutas coincidentes, por ejemplo, `your-app-rootpath/freecodecamp/echo`.
# --hints--
Test 1 : Your echo server should repeat words correctly
Prueba 1: Tu servidor de eco debe repetir las palabras correctamente
```js
(getUserInput) =>
@ -36,7 +36,7 @@ Test 1 : Your echo server should repeat words correctly
);
```
Test 2 : Your echo server should repeat words correctly
Prueba 2: Tu servidor de eco debe repetir las palabras correctamente
```js
(getUserInput) =>

View File

@ -1,6 +1,6 @@
---
id: 587d7fb1367417b2b2512bf3
title: Implement a Root-Level Request Logger Middleware
title: Implementa un Middleware de registro de peticiones a nivel raíz
challengeType: 2
forumTopicId: 301514
dashedName: implement-a-root-level-request-logger-middleware
@ -8,9 +8,9 @@ dashedName: implement-a-root-level-request-logger-middleware
# --description--
Earlier, you were introduced to the `express.static()` middleware function. Now its time to see what middleware is, in more detail. Middleware functions are functions that take 3 arguments: the request object, the response object, and the next function in the applications request-response cycle. These functions execute some code that can have side effects on the app, and usually add information to the request or response objects. They can also end the cycle by sending a response when some condition is met. If they dont send the response when they are done, they start the execution of the next function in the stack. This triggers calling the 3rd argument, `next()`.
Anteriormente, se te presentó la función de middleware `express.static()`. Ahora es el momento de ver lo que es un middleware con más detalle. Las funciones de Middleware son funciones que toman 3 argumentos: el objeto de la petición, el objeto de respuesta y la siguiente funcn en el ciclo petición-respuesta de la aplicación. Estas funciones ejecutan algún código que puede tener efectos secundarios en la aplicación, y normalmente agregan información a los objetos de la petición o respuesta. También pueden terminar el ciclo enviando una respuesta cuando se cumple alguna condición. Si no envían la respuesta cuando han terminado, comienzan la ejecución de la siguiente función en la pila de ejecución. Esto hace que se llame al tercer argumento, `next()`.
Look at the following example:
Veamos el siguiente ejemplo:
```js
function(req, res, next) {
@ -19,17 +19,17 @@ function(req, res, next) {
}
```
Lets suppose you mounted this function on a route. When a request matches the route, it displays the string “Im a middleware…”, then it executes the next function in the stack. In this exercise, you are going to build root-level middleware. As you have seen in challenge 4, to mount a middleware function at root level, you can use the `app.use(<mware-function>)` method. In this case, the function will be executed for all the requests, but you can also set more specific conditions. For example, if you want a function to be executed only for POST requests, you could use `app.post(<mware-function>)`. Analogous methods exist for all the HTTP verbs (GET, DELETE, PUT, …).
Supongamos que montaste esta funcn en una ruta. Cuando una solicitud coincide con la ruta, muestra la cadena “I'm a middleware…”, luego ejecuta la siguiente función en la pila de ejecución. En este ejercicio, vas a construir un middleware a nivel raíz. Como has visto en el desafío 4, para montar una función middleware a nivel raíz, puedes usar el método `app.use(<mware-function>)`. En este caso, la función se ejecutará para todas las peticiones, pero también se pueden establecer condiciones más específicas. Por ejemplo, si quieres que una función se ejecute sólo para solicitudes POST, puedes usar `app.post(<mware-function>)`. Existen métodos análogos para todos los verbos HTTP (GET, DELETE, PUT, …).
# --instructions--
Build a simple logger. For every request, it should log to the console a string taking the following format: `method path - ip`. An example would look like this: `GET /json - ::ffff:127.0.0.1`. Note that there is a space between `method` and `path` and that the dash separating `path` and `ip` is surrounded by a space on both sides. You can get the request method (http verb), the relative route path, and the callers ip from the request object using `req.method`, `req.path` and `req.ip`. Remember to call `next()` when you are done, or your server will be stuck forever. Be sure to have the Logs opened, and see what happens when some request arrives.
Construye un simple registrador. Para cada petición, debe registrar en la consola una cadena con el siguiente formato: `method path - ip`. Un ejemplo se vería así: `GET /json - ::ffff:127.0.0.1`. Ten en cuenta que hay un espacio entre `method` y `path` y que el guión que separa `path` e `ip` está rodeado por un espacio en ambos lados. Puedes obtener el método de solicitud (http verb), la ruta de ruta relativa y la ip del cliente desde el objeto de la petición usando `req.method`, `req.path` y `req.ip`. Recuerda llamar a `next()` cuando hayas terminado, o tu servidor permanecerá bloqueado permanentemente. Asegúrate de tener abiertos los "registros" y comprueba lo que sucede cuando llega una solicitud.
**Note:** Express evaluates functions in the order they appear in the code. This is true for middleware too. If you want it to work for all the routes, it should be mounted before them.
**Nota:** Express evalúa las funciones en el orden en que aparecen en el código. Esto también es cierto para los middleware. Si quieres que funcione para todas las rutas, debe montarse antes que ellas.
# --hints--
Root level logger middleware should be active
El middleware de registro a nivel raíz debe estar activo
```js
(getUserInput) =>

View File

@ -1,6 +1,6 @@
---
id: 587d7fb0367417b2b2512bef
title: Serve an HTML File
title: Sirve un archivo HTML
challengeType: 2
forumTopicId: 301516
dashedName: serve-an-html-file
@ -8,7 +8,7 @@ dashedName: serve-an-html-file
# --description--
You can respond to requests with a file using the `res.sendFile(path)` method. You can put it inside the `app.get('/', ...)` route handler. Behind the scenes, this method will set the appropriate headers to instruct your browser on how to handle the file you want to send, according to its type. Then it will read and send the file. This method needs an absolute file path. We recommend you to use the Node global variable `__dirname` to calculate the path like this:
Puedes responder a peticiones con un archivo utilizando el método `res.sendFile(path)`. Puedes ponerlo dentro del gestor de rutas `app.get('/', ...)`. En segundo plano, este método establecerá las cabeceras apropiadas para indicar a tu navegador cómo manejar el archivo que se desea enviar, de acuerdo a su tipo. Entonces leerá y enviará el archivo. Este método necesita una ruta de archivo absoluta. Te recomendamos que uses la variable global de Node `__dirname` para calcular la ruta como esta:
```js
absolutePath = __dirname + relativePath/file.ext
@ -16,13 +16,13 @@ absolutePath = __dirname + relativePath/file.ext
# --instructions--
Send the `/views/index.html` file as a response to GET requests to the `/` path. If you view your live app, you should see a big HTML heading (and a form that we will use later…), with no style applied.
Envía el archivo `/views/index.html` como respuesta a las solicitudes GET a la ruta `/`. Si ves tu aplicación en vivo, debes ver un gran encabezado HTML (y un formulario que usaremos más adelante…), sin ningún estilo aplicado.
**Note:** You can edit the solution of the previous challenge or create a new one. If you create a new solution, keep in mind that Express evaluates routes from top to bottom, and executes the handler for the first match. You have to comment out the preceding solution, or the server will keep responding with a string.
**Nota:** Puedes editar la solución del desafío anterior o crear uno nuevo. Si creas una nueva solución, ten en cuenta que Express evalúa las rutas de arriba a abajo, y ejecuta el manejador para la primera coincidencia. Tienes que comentar la solución anterior, o el servidor seguirá respondiendo con una cadena.
# --hints--
Your app should serve the file views/index.html
Tu app debe servir el archivo views/index.html
```js
(getUserInput) =>

View File

@ -1,6 +1,6 @@
---
id: 587d7fb1367417b2b2512bf1
title: Serve JSON on a Specific Route
title: Sirve JSON en una ruta específica
challengeType: 2
forumTopicId: 301517
dashedName: serve-json-on-a-specific-route
@ -8,17 +8,17 @@ dashedName: serve-json-on-a-specific-route
# --description--
While an HTML server serves HTML, an API serves data. A <dfn>REST</dfn> (REpresentational State Transfer) API allows data exchange in a simple way, without the need for clients to know any detail about the server. The client only needs to know where the resource is (the URL), and the action it wants to perform on it (the verb). The GET verb is used when you are fetching some information, without modifying anything. These days, the preferred data format for moving information around the web is JSON. Simply put, JSON is a convenient way to represent a JavaScript object as a string, so it can be easily transmitted.
Mientras que un servidor HTML sirve HTML, una API sirve datos. Una API <dfn>REST</dfn> (REpresentational State Transfer) permite el intercambio de datos de una manera sencilla, sin necesidad de que los clientes conozcan ningún detalle sobre el servidor. El cliente sólo necesita saber dónde está el recurso (la URL), y la acción que quiere realizar en él (el verbo). El verbo GET se utiliza cuando se obtiene alguna información, sin modificar nada. En la actualidad, el formato de datos preferido para mover información por la web es JSON. En pocas palabras, JSON es una manera conveniente de representar un objeto JavaScript como una cadena de texto, por lo que puede ser fácilmente transmitido.
Let's create a simple API by creating a route that responds with JSON at the path `/json`. You can do it as usual, with the `app.get()` method. Inside the route handler, use the method `res.json()`, passing in an object as an argument. This method closes the request-response loop, returning the data. Behind the scenes, it converts a valid JavaScript object into a string, then sets the appropriate headers to tell your browser that you are serving JSON, and sends the data back. A valid object has the usual structure `{key: data}`. `data` can be a number, a string, a nested object or an array. `data` can also be a variable or the result of a function call, in which case it will be evaluated before being converted into a string.
Vamos a crear una API simple creando una ruta que responda con JSON en la ruta `/json`. Puedes hacerlo como de costumbre, con el método `app.get()`. Dentro del manejador de ruta, utiliza el método `res.json()`, pasando un objeto como argumento. Este método cierra el bucle de solicitud y respuesta, devolviendo los datos. Tras bambalinas, convierte un objeto JavaScript en una cadena, luego establece las cabeceras apropiadas para decirle a tu navegador que está sirviendo JSON, y devuelve los datos. Un objeto válido tiene la estructura habitual `{key: data}`. `data` puede ser un número, una cadena de texto, un objeto anidado o un arreglo. `data` también puede ser una variable o el resultado de una llamada a una función, en cuyo caso será evaluado antes de ser convertido en una cadena de texto.
# --instructions--
Serve the object `{"message": "Hello json"}` as a response, in JSON format, to GET requests to the `/json` route. Then point your browser to `your-app-url/json`, you should see the message on the screen.
Sirve el objeto `{"message": "Hello json"}` como respuesta, en formato JSON, a las solicitudes GET en la ruta `/json`. A continuación, apunta tu navegador a `your-app-url/json`, debes ver el mensaje en la pantalla.
# --hints--
The endpoint `/json` should serve the json object `{"message": "Hello json"}`
El endpoint `/json` debe servir el objeto json `{"message": "Hello json"}`
```js
(getUserInput) =>

View File

@ -1,6 +1,6 @@
---
id: 587d7fb0367417b2b2512bf0
title: Serve Static Assets
title: Sirve recursos estáticos
challengeType: 2
forumTopicId: 301518
dashedName: serve-static-assets
@ -8,21 +8,21 @@ dashedName: serve-static-assets
# --description--
An HTML server usually has one or more directories that are accessible by the user. You can place there the static assets needed by your application (stylesheets, scripts, images).
Un servidor HTML normalmente tiene uno o más directorios a los que el usuario puede acceder. Puedes colocar allí los recursos estáticos que necesite tu aplicación (hojas de estilo, scripts, imágenes).
In Express, you can put in place this functionality using the middleware `express.static(path)`, where the `path` parameter is the absolute path of the folder containing the assets.
En Express, puedes poner en marcha esta funcionalidad utilizando el middleware `express.static(path)`, donde el parámetro `path` es la ruta absoluta de la carpeta que contiene los recursos.
If you dont know what middleware is... dont worry, we will discuss in detail later. Basically, middleware are functions that intercept route handlers, adding some kind of information. A middleware needs to be mounted using the method `app.use(path, middlewareFunction)`. The first `path` argument is optional. If you dont pass it, the middleware will be executed for all requests.
Si no sabes qué es middleware... no te preocupes, hablaremos en detalle más adelante. Básicamente, middleware son funciones que interceptan los manejadores de rutas, añadiendo algún tipo de información. Un middleware necesita ser montado usando el método `app.use(path, middlewareFunction)`. El primer argumento de `path` es opcional. Si no lo pasas, el middleware se ejecutará para todas las peticiones.
# --instructions--
Mount the `express.static()` middleware to the path `/public` with `app.use()`. The absolute path to the assets folder is `__dirname + /public`.
Monta el middleware `express.static()` a la ruta `/public` con `app.use()`. La ruta absoluta a la carpeta de recursos es `__dirname + /public`.
Now your app should be able to serve a CSS stylesheet. Note that the `/public/style.css` file is referenced in the `/views/index.html` in the project boilerplate. Your front-page should look a little better now!
Ahora tu aplicación debe ser capaz de servir una hoja de estilos CSS. Ten en cuenta que el archivo `/public/style.css` está referenciado en el archivo `/views/index.html` en el plantilla del proyecto. ¡Tu página principal debería verse un poco mejor ahora!
# --hints--
Your app should serve asset files from the `/public` directory to the `/public` path
Tu aplicación debe servir archivos de recursos desde el directorio `/public` a la ruta `/public`
```js
(getUserInput) =>

View File

@ -1,6 +1,6 @@
---
id: 587d7fb0367417b2b2512bee
title: Start a Working Express Server
title: Inicia un servidor Express
challengeType: 2
forumTopicId: 301519
dashedName: start-a-working-express-server
@ -8,9 +8,9 @@ dashedName: start-a-working-express-server
# --description--
In the first two lines of the file `myApp.js`, you can see how easy it is to create an Express app object. This object has several methods, and you will learn many of them in these challenges. One fundamental method is `app.listen(port)`. It tells your server to listen on a given port, putting it in running state. For testing reasons, we need the app to be running in the background so we added this method in the `server.js` file for you.
En las primeras dos líneas del archivo `myApp.js`, puedes ver lo fácil que es crear un objeto app Express. Este objeto tiene varios métodos, y aprenderás muchos de ellos en estos desafíos. Un método fundamental es `app.listen(port)`. Le dice a tu servidor que escuche en un puerto determinado, poniéndolo en estado de ejecución. Por razones de prueba, necesitamos que la aplicación se ejecute en segundo plano, así que añadimos este método en el archivo `server.js` para ti.
Lets serve our first string! In Express, routes takes the following structure: `app.METHOD(PATH, HANDLER)`. METHOD is an http method in lowercase. PATH is a relative path on the server (it can be a string, or even a regular expression). HANDLER is a function that Express calls when the route is matched. Handlers take the form `function(req, res) {...}`, where req is the request object, and res is the response object. For example, the handler
¡Sirvamos nuestra primer cadena! En Express, las rutas toman la siguiente estructura: `app.METHOD(PATH, HANDLER)`. METHOD es un método http en minúsculas. PATH es una ruta relativa en el servidor (puede ser una cadena, o incluso una expresión regular). HANDLER es una función que Express llama cuando la ruta coincide. Los Handlers toman la forma `function(req, res) {...}`, donde req es el objeto de la solicitud, y res es el objeto de respuesta. Por ejemplo, el handler
```js
function(req, res) {
@ -18,17 +18,17 @@ function(req, res) {
}
```
will serve the string 'Response String'.
servirá la cadena 'Response String'.
# --instructions--
Use the `app.get()` method to serve the string "Hello Express" to GET requests matching the `/` (root) path. Be sure that your code works by looking at the logs, then see the results in the preview if you are using Replit.
Utiliza el método `app.get()` para servir la cadena "Hello Express" a las peticiones GET que coincidan con la ruta `/` (raíz). Asegúrate de que tu código funciona mirando los registros, luego ve los resultados en la vista previa si estás usando Replit.
**Note:** All the code for these lessons should be added in between the few lines of code we have started you off with.
**Nota:** Todo el código de estas lecciones debe añadirse entre las pocas líneas de código con las que hemos iniciado.
# --hints--
Your app should serve the string 'Hello Express'
Tu aplicación debe mostrarte en consola la cadena 'Hello Express'
```js
(getUserInput) =>

View File

@ -1,6 +1,6 @@
---
id: 587d7fb2367417b2b2512bf7
title: Use body-parser to Parse POST Requests
title: Usa body-parser para analizar las peticiones POST
challengeType: 2
forumTopicId: 301520
dashedName: use-body-parser-to-parse-post-requests
@ -8,9 +8,9 @@ dashedName: use-body-parser-to-parse-post-requests
# --description--
Besides GET, there is another common HTTP verb, it is POST. POST is the default method used to send client data with HTML forms. In REST convention, POST is used to send data to create new items in the database (a new user, or a new blog post). You dont have a database in this project, but you are going to learn how to handle POST requests anyway.
Además de GET, hay otro verbo HTTP común, es POST. POST es el método por defecto utilizado para enviar datos del cliente con formularios HTML. En la convención REST, POST se utiliza para enviar datos para crear nuevos elementos en la base de datos (un nuevo usuario, o una nueva entrada de blog). No tienes una base de datos en este proyecto, pero de todos modos aprenderás a manejar las peticiones POST.
In these kind of requests, the data doesnt appear in the URL, it is hidden in the request body. The body is a part of the HTTP request, also called the payload. Even though the data is not visible in the URL, this does not mean that it is private. To see why, look at the raw content of an HTTP POST request:
En este tipo de peticiones, los datos no aparecen en la URL, están ocultos en el cuerpo de la petición. El cuerpo es parte de la petición HTTP, también llamada la carga útil. Aunque los datos no son visibles en la URL, esto no significa que sean privados. Para ver por qué, mire el contenido bruto de una petición HTTP POST:
```http
POST /path/subpath HTTP/1.0
@ -22,19 +22,19 @@ Content-Length: 20
name=John+Doe&age=25
```
As you can see, the body is encoded like the query string. This is the default format used by HTML forms. With Ajax, you can also use JSON to handle data having a more complex structure. There is also another type of encoding: multipart/form-data. This one is used to upload binary files. In this exercise, you will use a urlencoded body. To parse the data coming from POST requests, you have to install the `body-parser` package. This package allows you to use a series of middleware, which can decode data in different formats.
Como puedes ver, el cuerpo está codificado como la cadena de consulta. Este es el formato por defecto utilizado por los formularios HTML. Con Ajax, también puedes utilizar JSON para manejar datos con una estructura más compleja. También hay otro tipo de codificación: multiparte/form-data. Este se utiliza para subir archivos binarios. En este ejercicio, usarás un cuerpo urlencoded. Para analizar los datos provenientes de peticiones POST, tienes que instalar el paquete `body-parser`. Este paquete te permite usar una serie de middleware, que pueden decodificar datos en diferentes formatos.
# --instructions--
Install the `body-parser` module in your `package.json`. Then, `require` it at the top of the file. Store it in a variable named `bodyParser`. The middleware to handle urlencoded data is returned by `bodyParser.urlencoded({extended: false})`. Pass the function returned by the previous method call to `app.use()`. As usual, the middleware must be mounted before all the routes that depend on it.
Instala el módulo `body-parser` en tu `package.json`. Luego, agrega `require` en la parte superior del archivo con el nuevo módulo. Almacénelo en una variable llamada `bodyParser`. El middleware para manejar datos urlencoded es devuelto por `bodyParser.urlencoded({extended: false})`. Pasa la función devuelta por el método anterior llamada a `app.use()`. Como de costumbre, el middleware debe ser montado antes de todas las rutas que dependen de él.
**Note:** `extended` is a configuration option that tells `body-parser` which parsing needs to be used. When `extended=false` it uses the classic encoding `querystring` library. When `extended=true` it uses `qs` library for parsing.
**Nota:** `extended` es una opción de configuración que le dice a `body-parser` qué análisis necesita ser usado. Cuando `extended=false`, utiliza la biblioteca `querystring` de codificación clásica. Cuando `extended=true` utiliza la biblioteca `qs` para analizar la sintaxis.
When using `extended=false`, values can be only strings or arrays. The object returned when using `querystring` does not prototypically inherit from the default JavaScript `Object`, which means functions like `hasOwnProperty`, `toString` will not be available. The extended version allows more data flexibility, but it is outmatched by JSON.
Cuando se utiliza `extended=false`, los valores sólo pueden ser cadenas o arreglos. El objeto devuelto al usar `querystring` no hereda de forma prototípica del `Object` de JavaScript por defecto, lo que significa que funciones como `hasOwnProperty`, `toString` no estarán disponibles. La versión "extended" permite más flexibilidad de datos, pero es superada por JSON.
# --hints--
The 'body-parser' middleware should be mounted
El middleware 'body-parser' debe ser montado
```js
(getUserInput) =>

View File

@ -1,6 +1,6 @@
---
id: 587d7fb1367417b2b2512bf2
title: Use the .env File
title: Usa el archivo .env
challengeType: 2
forumTopicId: 301521
dashedName: use-the--env-file
@ -8,23 +8,25 @@ dashedName: use-the--env-file
# --description--
The `.env` file is a hidden file that is used to pass environment variables to your application. This file is secret, no one but you can access it, and it can be used to store data that you want to keep private or hidden. For example, you can store API keys from external services or your database URI. You can also use it to store configuration options. By setting configuration options, you can change the behavior of your application, without the need to rewrite some code.
El archivo `.env` es un archivo oculto que se utiliza para pasar variables de entorno a la aplicación. Este archivo es secreto, solamente tú puedes acceder a él, y puede ser utilizado para almacenar datos que desees mantener privados u ocultos. Por ejemplo, puedes almacenar claves de APIs de servicios externos o la URI de tu base de datos. También puedes usarlo para guardar opciones de configuración. Modificando las opciones de configuración, puedes cambiar el comportamiento de tu aplicación, sin necesidad de reescribir código.
The environment variables are accessible from the app as `process.env.VAR_NAME`. The `process.env` object is a global Node object, and variables are passed as strings. By convention, the variable names are all uppercase, with words separated by an underscore. The `.env` is a shell file, so you dont need to wrap names or values in quotes. It is also important to note that there cannot be space around the equals sign when you are assigning values to your variables, e.g. `VAR_NAME=value`. Usually, you will put each variable definition on a separate line.
Las variables de entorno son accesibles desde la aplicación como `process.env.VAR_NAME`. El objeto `process.env` es un objeto global de Node, y las variables son pasadas como cadenas de texto. Por convención, los nombres de las variables son en letras mayúsculas, con las palabras separadas por guión bajo. El archivo `.env` es un archivo shell, por lo que no es necesario incluir los nombres o valores entre comillas. También es importante tener en cuenta que no pueden haber espacios alrededor del signo de igual cuando se asignan valores a las variables, por ejemplo: `VAR_NAME=value`. Normalmente, usted pondrá cada definición de variable en una línea separada.
# --instructions--
Let's add an environment variable as a configuration option.
Añadamos una variable de entorno como opción de configuración.
Create a `.env` file in the root of your project directory, and store the variable `MESSAGE_STYLE=uppercase` in it.
Crea un archivo `.env` en la raíz del directorio de tu proyecto y almacena la variable `MESSAGE_STYLE=uppercase` en él.
Then, in the `/json` GET route handler you created in the last challenge, transform the response object's message to uppercase if `process.env.MESSAGE_STYLE` equals `uppercase`. The response object should either be `{"message": "Hello json"}` or `{"message": "HELLO JSON"}`, depending on the `MESSAGE_STYLE` value.
Luego, en el manejador de rutas `/json` GET creado en el último desafío, transforma el mensaje del objeto de respuesta a mayúsculas si `process.env.MESSAGE_STYLE` es igual a `uppercase`. El objeto de respuesta debe ser `{"message": "Hello json"}` o `{"message": "HELLO JSON"}`, dependiendo del valor `MESSAGE_STYLE`.
**Note:** If you are using Replit, you cannot create a `.env` file. Instead, use the built-in <dfn>SECRETS</dfn> tab to add the variable.
**Nota:** Si estás usando Replit, no puedes crear un archivo `.env`. En su lugar, utiliza la pestaña integrada <dfn>SECRETS</dfn> para añadir la variable.
Si estás trabajando localmente, necesitarás el paquete `dotenv`. Carga variables de entorno desde tu archivo `.env` en `process.env`. Instálalo con `npm install dotenv`. Luego, en la parte superior de tu archivo `myApp.js`, importa y carga las variables con `require('dotenv').config()`.
# --hints--
The response of the endpoint `/json` should change according to the environment variable `MESSAGE_STYLE`
La respuesta del endpoint `/json` debe cambiar de acuerdo a la variable de entorno `MESSAGE_STYLE`
```js
(getUserInput) =>