markdown 挑战03:RESTful和Express路由器

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown 挑战03:RESTful和Express路由器相关的知识,希望对你有一定的参考价值。

For this challenge, you'll add the save and delete features. And, you'll move the endpoints into a router.

## Requirements

* Swap out the custom logger with [Morgan](https://github.com/expressjs/morgan)
* Move endpoints to an Express Router
* Implement save a new Note feature
* Implement delete a Note feature

Before getting started, remember to create a development branch `git checkout -b feature/restful-routers` to hold your work.

## Swap out your custom logger with Morgan

Let's replace your custom logger with Morgan, a popular HTTP request logger middleware for Node.

You have installed NPM packages before so we'll skip with step-by-step instructions and simply provide a friendly reminder, then you can do your thing.

Remember that in NPM v5.x and up, saving the package to the dependencies property is now the default, so the `--save` flag is optional. But it is good practice to double-check the `dependencies` property in the `package.json` file to ensure the package was added correctly.

You're up!

* NPM install [Morgan](https://github.com/expressjs/morgan) and configure it to use the `dev` [predefined format](https://github.com/expressjs/morgan#predefined-formats).
* Verify Morgan is logging requests properly by hitting various endpoints using Postman and check the terminal for output.
  * Call a static file. Does it log the request?
  * Call the GET `/api/notes` and `/api/notes/:id/ endpoints. Does it log the requests as expected?
  * Call the GET or PUT `/does/not/exist`. Does it log the 404 response?
  
> Note: Morgan does **not** write the log to the console immediately. Instead, it buffers the log until the reponse has been sent so that it can log the response code, content length, etc. You may notice that the log files are written **after** other `console.log(...)` statements in your application.

Commit your changes!

## Move endpoints to Express Router

The `server.js` file is beginning to look a bit cluttered. Let's fix that by using [Express Router](https://expressjs.com/en/guide/routing.html#express-router) to create maintanable, modular, mountable route handlers.

Your challenge is create and mount an Express router for `/api/notes` and verify it works properly. You worked on [Modularizing with Express Router
](https://courses.thinkful.com/node-001v5/assignment/1.4.6) in the curriculum so we won't repeat the details here, but we have provided a list of the changes below. You can refer back to the assignment in the curriculum and Express Router documentation if needed.

* Create `/router/notes.router.js` folder and file.
* In `/router/notes.router.js`:
  * Require Express
  * Create a Router
  * Move the `simDb` related code from `server.js` the router file
  * Move the endpoints from `server.js` to the router file
  * Change `app.METHOD` to `router.METHOD`
  * Export the router
* In `/server.js`:
  * Mount the router with `app.use(...)`

Before proceeding you should verify the changes by hitting each endpoint using Postman and check the results.

* Does it return the correct data?
* Does the Morgan still log correctly?

Mount the notes router on `/api` and remove `/api` from the endpoint paths:

* In `server.js`, mount the router on `/api`:
  * change `app.use(notesRouter)` to `app.use('/api', notesRouter)`
* And in `notes.router.js` remove `/api` from endpoints:
  * change `router.get('/api/notes',...` to `router.get('/notes',...`
  * change `router.get('/api/notes/:id',...` to `router.get('/notes/:id',...`

Confirm the changes are working properly by hitting each endpoint again using Postman.

Commit your changes!

## Create new POST and DELETE endpoints

Congrats! Now let's implement the `post` and `delete` endpoints. We'll walk you thru the creating the new Note feature so you'll be able to implement the delete Note feature on your own.

### Update the Server

In the notes router, create a POST `/notes` endpoint. Notice the similarities and differences between the POST and PUT endpoints.

```js
// Post (insert) an item
router.post('/notes', (req, res, next) => {
  const { title, content } = req.body;

  const newItem = { title, content };
  /***** Never trust users - validate input *****/
  if (!newItem.title) {
    const err = new Error('Missing `title` in request body');
    err.status = 400;
    return next(err);
  }

  notes.create(newItem, (err, item) => {
    if (err) {
      return next(err);
    }
    if (item) {
      res.location(`http://${req.headers.host}/notes/${item.id}`).status(201).json(item);
    } else {
      next();
    }
  });
});
```

Use Postman to create a new Note and confirm the endpoint is working. Then call the GET `/notes` endpoint. Does the new note show up in the list? When you call GET `/notes/:id` with the new ID, does it return?

Commit your changes!

## Add Delete Note

Your Turn!

Your challenge is to implement the delete note feature and test it with Postman

Requirements:

* Should match requests to DELETE `/api/notes/:id`
* Should delete the note from `simDb` using `notes.delete( id, err => {})`
* If note is deleted then respond with status 204 "No Content"
* If error is detected, then respond with status 500 and the error

Commit your changes!

## Update Client

Your last task is to simple update the client to take advantage of the new features. Instead of making piecemeal changes, you can copy the code for `public/scripts/api.js` and `public/scripts/noteful.js` from this gist.

[Feature / Noteful App V1 POST and DELETE Client update](https://gist.github.com/cklanac/cc49a81bd14dd4c6c2d9b95ab805a782)

## Solutions

You can view an example solution and compare the differences between branches

* Solution: You can find the example solution in the `solution/03-restful` branch in the upstream repo.
* [Compare this solution branch to the previous](https://github.com/Thinkful-Ed/noteful-app-v1/compare/solution/solution/02-middleware...03-restful)


Good Luck!

以上是关于markdown 挑战03:RESTful和Express路由器的主要内容,如果未能解决你的问题,请参考以下文章

markdown 用于测试/调试HTTP(S)和restAPI(RESTful)的HTTP(S)基准测试工具/工具包

markdown RESTful模块

markdown Servicios Web RESTful.md

云服务OpenAPI设计7大挑战(上)

markdown 值得关注的挑战指数

markdown Certbot与DNS挑战