[ExpressJS] Lesson 10 – Writing Code to Operate Personal Blog (Continued)

Tram Ho

Before we start writing the detailed handling code for the `/article/add` route, let’s take a moment to look at the `tempate` code of the new article editor interface built into the Sub-Series EJS. . “`express-blog/view/component/article/add.js <form id=”article” action=” ” method=”post”>

Category <% for (var category of data.get(“category-list”)) { %> <option value=” “> <%= category.get(“name”) %> <% } %>

“` So the operating code for this `route` will need to provide `template` with the complete list of categories at the `category-list` key and the path at the `endpoint` key to point to. `router` handles a request to save a new record to `database`. ## Add a router First of all we need to declare a new `router` at the `index` of the `route/article` group. “`route/article/index.js var express = require(‘express’); var router = express.Router(); router.use(“/view”, require(“./action/view”)); router.use(“/add”, require(“./action/add”)); module.exports = router; “` ## Route processing overview “`route/article/action/add.js router.get(“/”, async (request, response, next) => { var data = new Data(); await getDataForTopnav(data); await getDataForArticle(data, “add”); data.set(“endpoint”, “/article/add”); response.render(“index”, { layout: “article”, action: “add “, data }); }); // router.get “` The path `endpoint` here I set as `/article/add` to point back to this exact `router`. And so when editing the article and pressing the “Post” button, we will have a `post` request received as follows: “`route/article/action/add.js router.get(” /”, async (request, response, next) => { // — request to see the new article editor interface }); router.post(“/”, async (request, response, next) => { // — request to save new posts to database }); “` ## get-data-for-article In the processing code of `sub-procedure` that queries data for the `#article` area, we continue to add branching logic for `action == “add “`. “`route/sub-procedure/get-data-for-article.js module.exports = async ( in_data = new Data(), in_action = “view”, /* view | add | edit */ in_id = “Infinity ” ) => { if (in_action == “view”) await getArticle(in_data, in_id); else if (in_action == “add”) await getCategoryList(in_data); else throw new Error(“Unsupported action type”); }; /* getArticle… */ const getCategoryList = async ( out_data = new Data() ) => { var categoryList = []; await databaseManager.execute( Category.name, “select”, categoryList, Infinity, “default” ); out_data.set(“category-list”, categoryList); }; “` ## Run test test “`CMD|Terminal.io npm test Server started “` [http://localhost:8080/article/add](http://localhost:8080/article/add) ![](https://images.viblo.asia/905b0a98-8d89-4e96-8e70-90c3a57de5b6.png) ## Retrieve form submission To extract submission data from ` ` input data about `server` as `object`, we can rely on the help of two `middleware` preprocessors provided by ExpressJS by default `express.json()` and `express.urlencoded( )`. These `middleware` need to be appended before the `routers` that handle `form` so we will always append at `app.js` for common use by all handler routes. “`express-blog/app.js /* — Utility Middlewares */ app.use(logger(“dev”)); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(pathToPublicFolder)); /* — Adding Routers… */ “` And now we can access the `name/value` pairs due to the `s. ` sent back via `request.body`. “`route/article/action/add.js /* — Receive Submitted */ router.post(“/”, async (request, response, next) => { console.log(request.body); } ); “` And now we will try to edit a new post and then click “Post” to see the information received in `request.body` display in `console`. “`CMD|Terminal.io npm test Server started “` [http://localhost:8080/article/add](http://localhost:8080/article/add) ![](https://images .viblo.asia/6c75e7a5-6c64-4b74-b35e-b7ce965b9fc2.png) Click the “Post” button: ![](https://images.viblo.asia/578ec77c-3920-4d60-a3b4-38314619d3ae.png) ## Post Request Processing Overview What we need to do here is to create an `object` describing a new record `Article` without `@id` because it has not been saved to `database`. Then tell `databaseManager` to write data to `data` directory. If necessary, you can save additional time information in the `edited-datetime` key of the `class Article`. Here I will only save the information I have just received and do not add the system time query operation. After storing the new article’s data, we will have the value `@id` representing the new record and can navigate to the page displaying the article content `/article/view/ :id` with the `response.redirect(path)` method. “`route/article/action/add.js /* router.get()… */ router.post(“/”, async (request, response, next) => { var entries = Object.entries( request.body); var submitted = new Article(entries); var inserted = new Article(); await databaseManager.execute( Article.name, “insert”, submitted, inserted ); response.redirect(`/article/view/ ${inserted.get(“@id”)}`); }); // router.post module.exports = router; “` “`CMD|Terminal.io npm start Server start “` ![](https://images.viblo.asia/6e7310e1-99b7-426b-ac78-9e1eece7d19c.png) ## End of article So we’ve done the request handling code for the `/article/add` route including the request to see the new article editor interface and the request to store the new article in `database`. The handler method for the `/article/edit/:id` route to edit the content of an article is not much different so we won’t discuss the code in detail here. All you need to do is query the existing post’s data with the `id` parameter and load it in ` ` sent to the web browser. The route `article/delete/:id` is just a side feature of `edit` and can be supplemented with a link or a button in ` ` edit post. After deleting the post, you can redirect the user to the homepage or the category menu page. In the next articles, we will build a simple login and administration interface. [[EJS] Lesson 9 – Writing Code to Build Blog Interface (End)](https://viblo.asia/p/3Q75wAvDZWb) Then write the operating code to add this simple security feature to the blog and upload it to [Glitch.com](https://glitch.com/). (Coming soon) [[ExpressJS] Lesson 11 – Writing Code to run a Personal Blog (Continued)](#)

Share the news now

Source : Viblo