Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expanded guides for some APIs and Microservices challenges and fixed links to the source files #36131

Merged
merged 12 commits into from Jul 2, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -5,20 +5,49 @@ title: Chain Middleware to Create a Time Server

<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->

Similar to the last challenge, but now we are chaining 2 functions together. It seems complicated, but it's just javascript.
Similar to the last challenge, but now we are chaining 2 functions together. It seems complicated, but it's just JavaScript.

Instead of responding with the time we can also add a string to the request and pass it to the next function. This is trivial, but it makes for a decent example. The code looks like:
### Hint

Instead of responding with the time we can also add any arbitrary property to the request object and pass it to the next function by calling the `next()` method. This is trivial, but it makes for a decent example. The code will looks like this:

```javascript
app.get("/now", middleware(req, res, next) {
app.get("/now", (req, res, next) => {
// adding a new property to req object
// in the middleware function
req.string = "example";
next();
},
function (req, res) {
res.send(req.string); // This will display "example" to the user
}, (req, res) => {
// accessing the newly added property
// in the main function
res.send(req.string);
});
```

### Solution

```javascript
app.get("/now", (req, res, next) => {
req.time = new Date().toString();
next();
}, (req, res) => {
res.send({
time: req.time
});
});
```

You can also declare the middleware beforehand to use in multiple routes as shown below:

```javascript
const middleware = (req, res, next) => {
req.time = new Date().toString();
next();
};

<a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/apis-and-microservices/basic-node-and-express/chain-middleware-to-create-a-time-server/index.md' target='_blank' rel='nofollow'>Help our community expand these hints and guides</a>.
app.get("/now", middleware, (req, res) => {
res.send({
time: req.time
});
});
```
Expand Up @@ -5,16 +5,19 @@ title: Get Query Parameter Input from the Client

<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->

Given the hint after the stub, "/name?first=<firstname>&last=<lastname>," we can build the response like so:
Given the endpoint URL, `/name?first=firstname&last=lastname`, we can extract the query parameters (`first` and `last`) and their corresponding values from the `req.query` object and send a custom JSON response containing values derived from the query parameters to the client.

### Solution

```javascript
app.get("/name", function(req, res) {
var firstName = req.query.first;
var lastName = req.query.last;
// Send the json object
});
app.get("/name", function(req, res) {
var firstName = req.query.first;
var lastName = req.query.last;
// OR you can destructure and rename the keys
var { first: firstName, last: lastName } = req.query;
// Use template literals to form a formatted string
res.json({
name: `${firstName} ${lastName}`
});
});
```



<a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/apis-and-microservices/basic-node-and-express/get-query-parameter-input-from-the-client/index.md' target='_blank' rel='nofollow'>Help our community expand these hints and guides</a>.
Expand Up @@ -5,17 +5,31 @@ title: Get Route Parameter Input from the Client

<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->

If someone tells you to build a GET or POST you would do app.get(...) or app.post(...) accordingly. The basic structure of the challenge is:
If someone tells you to build a GET or POST endpoint you would achieve the same using `app.get(...)` or `app.post(...)` accordingly.

## Hint

In order to get route parameters from a POST request, the general format is as follows:

```javascript
app.get("/:word/echo", function(req, res) {
// word = req.params.word;
// respond with the json object
app.post("/:param1/:param2", (req, res) => {
// Access the corresponding key in the req.params
// object as defined in the endpoint
var param1 = req.params.parameter1;
// OR use destructuring to get multiple paramters
var { param1, param2 } = req.params;
// Send the req.params object as a JSON Response
res.json(req.params);
});
```

## Solution




<a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/apis-and-microservices/basic-node-and-express/get-route-parameter-input-from-the-client/index.md' target='_blank' rel='nofollow'>Help our community expand these hints and guides</a>.
```javascript
app.get("/:word/echo", (req, res) => {
const { word } = req.params;
res.json({
echo: word
});
});
```
Expand Up @@ -24,8 +24,5 @@ If you have trouble formatting the string correctly, one way to do it looks like
var string = req.method + ' ' + req.path + ' - ' + req.ip;
```


<a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/apis-and-microservices/basic-node-and-express/implement-a-root-level-request-logger-middleware/index.md' target='_blank' rel='nofollow'>Help our community expand these hints and guides</a>.

### Resources
- [Express Middleware](https://expressjs.com/en/guide/using-middleware.html)
Expand Up @@ -16,8 +16,3 @@ To serve an index.html in a folder called "public" at the root domain you would
```

Note: __dirname returns the root directory is a best practice for node developers.




<a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/apis-and-microservices/basic-node-and-express/serve-an-html-file/index.md' target='_blank' rel='nofollow'>Help our community expand these hints and guides</a>.
Expand Up @@ -5,16 +5,12 @@ title: Serve JSON on a Specific Route

<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->

It is rather simple to serve a json object with node (at the '/json' route), if we want to deliver a message and give it the value "Hello World," we can do so like this:
It is rather simple to serve a JSON object with Node (at the `/json` route), if we want to deliver an object containing a key `message` and with the value `"Hello json"` we can do so as indicated:

```javascript
app.get("/json", function(req, res) {
res.json({"message": "Hello World"});
});
app.get("/json", (req, res) => {
res.json({
"message": "Hello json"
});
});
```





<a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/apis-and-microservices/basic-node-and-express/serve-json-on-a-specific-route/index.md' target='_blank' rel='nofollow'>Help our community expand these hints and guides</a>.
Expand Up @@ -5,19 +5,18 @@ title: Serve Static Assets

<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->

Static webpages are fairly simple with express. This could be useful for building your own portfolio website or blog, etc.

To serve a static webpage from the "views" folder you can use code such as:

```javascript
const express = require("express");
const app = express();
app.use(express.static(__dirname + "/views"));
```

Serving static webpages and assets is fairly simple with `express`. This could be useful for building your own portfolio website or blog, single-page web applications etc.

To serve static assets from the `public` folder in the you can use the `express.static()` method as the middleware. This method takes the endpoint and the absolute path to the directory containing the static assets as arguments and exposes the files in that folder at the given endpoint. By default, if the endpoint is not passed to the method, the folder is exposed at the root endpoint i.e. `/` for the application.

The `__dirname` variable is a string containing the absolute path to the root of your project which has to be concatenated with the folder containing the assets.

Add the following line to your file above all defined routes to achieve the desired result:

```javascript
// Normal usage
app.use(express.static(__dirname + "/public"));

<a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/apis-and-microservices/basic-node-and-express/meet-the-node-console/index.md' target='_blank' rel='nofollow'>Help our community expand these hints and guides</a>.
// Assets at the /assets route
app.use("/assets", express.static(__dirname + "/public"));
```
Expand Up @@ -3,28 +3,20 @@ title: Start a Working Express Server
---
## Start a Working Express Server


<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->

If you had a website at "example.com/" and wanted to serve a string such as "Hello World" to whoever visits the root domain you could do so easily using node and/or express:
If you had a website at "example.com/" and wanted to serve a string such as "Hello Express" to whoever visits the root domain you could do so easily using Node and/or express:

```javascript
app.get("/", function(req, res) {
res.send("Hello World");
res.send("Hello Express");
});

```


Also, with ES6+ you can save some typing by using "=>" instead of "function," which looks like:
Also, with the modern ES6 syntax you can save a few keystrokes by using arrow functions:

```javascript
app.get("/", (req, res) => {
res.send("Hello World");
res.send("Hello Express");
});

```



<a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/apis-and-microservices/basic-node-and-express/start-a-working-express-server/index.md' target='_blank' rel='nofollow'>Help our community expand these hints and guides</a>.
Expand Up @@ -4,20 +4,39 @@ title: Use body-parser to Parse POST Requests
## Use body-parser to Parse POST Requests

<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->

The body-parser should already be added to your project if you used the provided boilerplate, but if not it should be there as:

```json
"dependencies": {
"body-parser": "^1.4.3",
"body-parser": "^1.19.0",
...
"express": "^4.17.1"
}
```

All you need to do for this challenge is pass the middleware to app.use(). Make sure it comes before the paths it needs to be used on. Remember that body-parser returns with `bodyParser.urlencoded({extended: false})`. Use the following as a template:
You can run `npm install body-parser` to add it as a dependency to your project instead of manually adding it to the `package.json` file.

This guide assumes you have imported the `body-parser` module into your file as `bodyParser`.

In order to import the same, you just need to add the following line at the top of your file:

```javascript
var bodyParser = require('body-parser');
```

All you need to do for this challenge is pass the middleware to `app.use()`. Make sure it comes before the paths it needs to be used on. Remember that body-parser returns with `bodyParser.urlencoded({extended: false})`. Use the following as a template:

```javascript
//app.use(middleware-function);
app.use(bodyParser.urlencoded({ extended: false }));
```

In order to parse JSON data sent in the POST request, use `bodyParser.json()` as the middleware as shown below:

```javascript
app.use(bodyParser.json());
```

<a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/apis-and-microservices/basic-node-and-express/use-body-parser-to-parse-post-requests/index.md' target='_blank' rel='nofollow'>Help our community expand these hints and guides</a>.
The data received in the request is available in the `req.body` object.

Do not forget that all these statements need to go above any routes that might have been defined.
Expand Up @@ -22,9 +22,3 @@ All we need to do now is check what the value of the environment variable is, wh
}
});
```





<a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/apis-and-microservices/basic-node-and-express/use-the-.env-file/index.md' target='_blank' rel='nofollow'>Help our community expand these hints and guides</a>.
Expand Up @@ -10,4 +10,4 @@ You should go over to the package.json file in your project. Versions follow a s
"version": "x.x.x"
```

<a href='https://github.com/freeCodeCamp/freeCodeCamp/blob/master/guide/english/certifications/apis-and-microservices/managing-packages-with-npm/add-a-version-to-your-package.json/index.md' target='_blank' rel='nofollow'>Help our community expand these hints and guides</a>.
This convention is also known as _**semantic versioning**_ where the versions follow the format `MAJOR.MINOR.PATCH` whenever a new release is made.
Expand Up @@ -4,14 +4,14 @@ title: Expand Your Project with External Packages from npm
## Expand Your Project with External Packages from npm

<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
You should go over to the `package.json` file in your project. Dependencies follow a similar convention as this:

The `package.json` file in the root directory of your project, among other things, lists all the dependencies that your project needs in order to work, are listed under the `dependencies` key in that file and follow a similar convention as given below:

```json
"dependencies": {
"express": "^4.16.4",
"helmet": "^3.14.0"
},
...
```

<a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/apis-and-microservices/managing-packages-with-npm/expand-your-project-with-external-packages-from-npm/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
There might be additional peer dependencies or development dependencies that your project might need in case it has to be built or compiled due to a number of reasons currently outside the scope of this challenge. They are listed under the `peerDependecies` and `devDependencies` respectively.