<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Wen on Medium]]></title>
        <description><![CDATA[Stories by Wen on Medium]]></description>
        <link>https://medium.com/@wenliangsu65018?source=rss-9abbd74e1a5c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1gung9E9HoBG8NMFbOIdvQ.jpeg</url>
            <title>Stories by Wen on Medium</title>
            <link>https://medium.com/@wenliangsu65018?source=rss-9abbd74e1a5c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 23:45:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wenliangsu65018/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Deploy Node.js and connect MySQL by fly.io]]></title>
            <link>https://medium.com/@wenliangsu65018/deploy-node-js-and-connect-mysql-by-fly-io-5d691afd5958?source=rss-9abbd74e1a5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d691afd5958</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[flyio]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[mysql-workbench]]></category>
            <category><![CDATA[deployment]]></category>
            <dc:creator><![CDATA[Wen]]></dc:creator>
            <pubDate>Mon, 15 May 2023 09:34:18 GMT</pubDate>
            <atom:updated>2023-05-15T09:34:18.904Z</atom:updated>
            <content:encoded><![CDATA[<p>When Heroku canceled its free policy last November, developers are looking for other small free deployment platforms to deploy their side projects. Currently, <a href="https://vercel.com/home">Vercel</a>, <a href="https://render.com/">Render</a>, and <a href="http://fly.io/">fly.io</a> are used to do this. The reason for choosing <a href="http://fly.io/">fly.io</a> this time is that I had read and attempted to deploy on it before, but failed. Now I have time to study the method of deployment in this platform.</p><h3><strong>Step for deploying the application (app)</strong></h3><ul><li><strong><em>Install CLI</em></strong></li></ul><p>Open your terminal and run the code below to install flyctl.</p><p>Homebrew:</p><pre>$ brew install flyctl</pre><p>Script:</p><pre>$ curl -L https://fly.io/install.sh | sh</pre><blockquote><em>Notice: The executed command</em> fly xxxx can be written in flyctl xxxx</blockquote><ul><li><strong><em>Sign up and Sign in</em></strong></li></ul><p>Sign up for the account and need to add the credit card number cause this platform will not allow you to pass the authentication when you deploy. After creating the account, run the code line below in your terminal.</p><pre>$ fly auth login</pre><p>and it will open the browser to log in to your account. After login successfully, it will show the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YhzMT_-gXNSrMhHf4priXA.png" /></figure><ul><li><strong><em>Launch the app to</em> </strong><a href="http://fly.io/"><strong><em>fly.io</em></strong></a></li></ul><p>Open the path of your app in the terminal and run the code as follows:</p><pre>$ fly launch</pre><p>and it shows some messages that you need to decide:</p><pre>- Choose an app name (leave blank to generate one)<br><br>- Choose a region for deployment<br><br>- Would you like to set up a Postgresql database now?<br><br>- Would you like to set up an Upstash Redis database now?<br><br>-  Would you like to deploy now?</pre><p>The app name only accepts lowercase letters, dashes, and numbers or you can leave it blank and it will generate itself. In the last message, I suggest that you don’t need to deploy your app immediately because your project folder also creates a new file (fly.toml) at the same time. The deployment configuration is in the toml file. You can read the official document to know what each parameter does in this file <a href="https://fly.io/docs/reference/configuration/">(app configuration in toml</a>). Here is an example toml file:</p><pre># fly.toml app configuration file generated for app_name on 2023-05-08T12:10:20+08:00<br>#<br># See https://fly.io/docs/reference/configuration/ for information about how to use this file.<br>#<br><br>app = &quot;your_app_name&quot;<br><br>kill_signal = &quot;SIGINT&quot;<br>kill_timeout = 5<br># Deploy region<br>primary_region = &quot;sin&quot;<br>processes = []<br><br>[env]<br>  PORT = &quot;8080&quot;<br>  NODE_ENV = &quot;production&quot;<br><br>[deploy]<br>  release_command = &quot;npx sequelize db:migrate&quot;<br><br>[experimental]<br>  auto_rollback = true<br><br>[[services]]<br>  http_checks = []<br>  internal_port = 8080<br>  processes = [&quot;app&quot;]<br>  protocol = &quot;tcp&quot;<br>  script_checks = []<br>  [services.concurrency]<br>    hard_limit = 25<br>    soft_limit = 20<br>    type = &quot;connections&quot;<br><br>  [[services.ports]]<br>    force_https = true<br>    handlers = [&quot;http&quot;]<br>    port = 80<br><br>  [[services.ports]]<br>    handlers = [&quot;tls&quot;, &quot;http&quot;]<br>    port = 443<br><br>  [[services.tcp_checks]]<br>    grace_period = &quot;1s&quot;<br>    interval = &quot;15s&quot;<br>    restart_limit = 0<br>    timeout = &quot;2s&quot;</pre><p>There is one thing you need to notice the connected PORT. The default value is 8080 and if you don’t change this, you have to set the same port value in your app.js.</p><ul><li><strong><em>Set the sensitive environmental variable</em></strong></li></ul><p>In toml file, it has a risk of security to write the secrete in [env]. You can run the code below in the terminal to set the secrets and <a href="http://fry.io/">fry.io</a> encrypt these data.</p><pre># Set the secret<br>flyctl secrets set FACEBOOK_SECRET=xxxxxxx<br><br># Remove the secret<br>flyctl secrets unset FACEBOOK_SECRET=xxxxxxx<br><br># show the list of secrets<br>flyctl secrets list</pre><ul><li><strong><em>Deploy the app in</em> <em>fly.io</em></strong></li></ul><p>After checking the configuration, you can start to deploy by running the code:</p><pre>$ fly deploy$ fly deploy</pre><p>You will see the figure if it deployed successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4EDd_bTjy_JV5w38fMLr3A.png" /></figure><p>You can go to the website fly.io to check the dashboard</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qH_roP4ytwOu9S0nXRbF_g.png" /></figure><p>or run the code to check it in terminal. It showed the example below.</p><pre>or run the code to check it in terminal. It showed the example below.</pre><pre># The result in terminal<br>App<br>  Name     = xxxxx                                        <br>  Owner    = personal                                              <br>  Hostname = xxxx.fly.dev                                <br>  Image    = xxxx:deployment-xxxxx<br>  Platform = machines                                              <br><br>Machines<br>ID             PROCESS VERSION REGION STATE   HEALTH CHECKS LAST UPDATED         <br>xxxxxxxxxxxxxx app     2       nrt    started               2023-05-08T02:46:04Z</pre><p>After deploying, you can run the code fly open to check the website of app.</p><h3><strong>Connect the database to your app (MySQL)</strong></h3><p>From the description of the document, the step to deploy the database as an app on fly.io. Some settings are a little different. Here are the steps:</p><p>1. <strong>Create an independent folder and launch it.</strong></p><p>The folder you can place it anywhere and run the code below:</p><pre># You can name the folder by yourself<br>mkdir flyio-mysql<br>cd flyio-mysql</pre><p>Then you have to run fly launch to launch the database to create the fly.toml. Of cause, you have to set the location of database.</p><p>2. <strong>Set some parameters and secrets</strong></p><p><strong><em>(a) Set the volume of database:</em></strong></p><p>Run the code to set the volume of your database and the unit is GB. You can set only 1 GB is your database is just for side projects.</p><pre># Create a volume named &quot;mysqldata&quot; within our app &quot;wen-mysql&quot;<br>fly volumes create mysqldata --size 1 # gb</pre><p>There is one thing you have to notice that this database can be shared by many apps. If you want to expense scale, you have to change the setting by following the document.</p><p><strong><em>(b) Set the secrets:</em></strong></p><p>Run the code as follows to set password of database</p><pre># Set secrets:<br># MYSQL_PASSWORD      - password set for user $MYSQL_USER<br># MYSQL_ROOT_PASSWORD - password set for user &quot;root&quot;<br><br>fly secrets set MYSQL_PASSWORD=xxxxx MYSQL_ROOT_PASSWORD=xxxxx</pre><p><strong><em>(c) Set the fly.toml file in database app</em></strong></p><p>Open your fry.toml and notice that your app is on V2 of fly platform. Here is the setting on V2 in official document. (It is a different setting if your app is on V1, please watch the official document.)</p><pre># fly.toml app configuration file generated for wen-mysql on 2023-05-08T22:00:35+08:00<br>#<br># See https://fly.io/docs/reference/configuration/ for information about how to use this file.<br>#<br><br>app = &quot;your_app_name&quot;<br>kill_signal = &quot;SIGINT&quot;<br>kill_timeout = 5<br><br># If copy/paste&#39;ing, adjust this<br># to the region you&#39;re deploying to<br>primary_region = &quot;sin&quot;<br><br>[processes]<br>app = &quot;--datadir /data/mysql --default-authentication-plugin mysql_native_password --performance-schema=OFF --innodb-buffer-pool-size 64M&quot;<br><br>[mounts]<br>  source=&quot;mysqldata&quot;<br>  destination=&quot;/data&quot;<br>  <br># MYSQL_DATABASE can name your database and will created aftering deploy<br>[env]<br>  MYSQL_DATABASE = &quot;some_db&quot; <br>  MYSQL_USER = &quot;non_root_user&quot;<br><br># As of 04/25/2023:<br># MySQL 8.0.33 has a bug in it<br># so avoid that specific version<br>[build]<br>  image = &quot;mysql:8.0.31&quot;</pre><p>In the parameter of [env], you can write the name of database and it will be created at the same time when the app is deployed. If you want to create the other database, you have to connect this app from outside to use the command in terminal or GUI tool.</p><p>3. <strong>Deploy the database and connect it by app</strong></p><p>Run the code fly deploy to deploy the database app and it shows the figure when deploying successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cQv0qz1jye0B-nDs2DVoww.png" /></figure><p>Then, open your app to which you want to connect to the database app and change the settings inside config.js and fly.toml.</p><p>At the section of production in config.js file, you need to adjust the name of database and host. The host is your name of database app with “.internal” appended. Here is an example of setting.</p><pre>{<br> &quot;development&quot;: {<br>  ...<br> },<br> &quot;test&quot;: {<br>  ...<br> },<br> &quot;production&quot;: {<br>  &quot;username&quot;: &quot;root&quot;,<br>  &quot;password&quot;: &quot;xxxx&quot;,<br>  &quot;database&quot;: &quot;your_database_name&quot;,<br>  &quot;host&quot;: &quot;database_app_name.internal&quot;,<br>  &quot;dialect&quot;: &quot;mysql&quot;<br> }<br>}</pre><p>In a MySQL database, you need to run migration or set a seeder in your app. Go to the fly.toml file in your app and check if it has a [deploy] section. Then, add the release_command and input the command that you want to run, such as npx sequelize db:migrate or nps sequelize db:seed. Finally, deploy the app. This command will be executed during deployment.</p><pre># fly.toml app configuration file generated for todo-sequelize on 2023-05-08T12:10:20+08:00<br>#<br># See https://fly.io/docs/reference/configuration/ for information about how to use this file.<br>#<br><br>app = &quot;todo-sequelize&quot;<br><br>kill_signal = &quot;SIGINT&quot;<br>kill_timeout = 5<br>primary_region = &quot;sin&quot;<br>processes = []<br><br>[env]<br>  PORT = &quot;8080&quot;<br>  NODE_ENV = &quot;production&quot;<br><br># only build one command when deploying<br># need to redeploying if you want to build the other command<br>[deploy]<br>  release_command = &quot;npx sequelize db:migrate&quot;<br>  <br>[experimental]<br>  auto_rollback = true<br><br>[[services]]<br>  http_checks = []<br>  internal_port = 8080<br>  processes = [&quot;app&quot;]<br>  protocol = &quot;tcp&quot;<br>  script_checks = []<br>  [services.concurrency]<br>    hard_limit = 25<br>    soft_limit = 20<br>    type = &quot;connections&quot;<br><br>  [[services.ports]]<br>    force_https = true<br>    handlers = [&quot;http&quot;]<br>    port = 80<br><br>  [[services.ports]]<br>    handlers = [&quot;tls&quot;, &quot;http&quot;]<br>    port = 443<br><br>  [[services.tcp_checks]]<br>    grace_period = &quot;1s&quot;<br>    interval = &quot;15s&quot;<br>    restart_limit = 0<br>    timeout = &quot;2s&quot;</pre><p>If you run the command successfully during deploying, it will show the image below.</p><p>However, there is only one command can be declared. If you want to run another command, you have to re-write therelease_command and deploy it again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*y7a_O1NJ10qfNZ6t0TZ3MA.png" /></figure><h3><strong>Connect the database app from outside(MySQL GUI)</strong></h3><p>In fly app platform, it is different from Heroku to connect database of MySQL. It sets the proxy as localhost to activate the database without URL. The default value of proxy is 3306 and you can run the code as follows:</p><pre># Default port is 3306 and you can run this code if it is not used<br>fly proxy 3306 -a wen-mysql<br><br># if port 3306 is used you can use this code to change the default port.<br>fly proxy 13306:3306 -a wen-mysql</pre><p>Most people set proxy 3306 to their MySQL. You can run the second code to do the same thing. and it will show the success as the following image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*WEJWA9TKa4t9ncw6xrVm1Q.png" /></figure><p><strong><em>Don’t turn off it</em></strong> and open your GUI tool to set the configuration as follows:</p><p>Now you can operate the database in GUI.</p><p>There is one thing you need to notice: the hostname is provided on the <a href="http://fly.io/">fly.io</a> dashboard. However, if you want to operate the remote database on your computer, you must execute fly commands through the CLI and activate your local IP address, 127.0.0.1. Therefore, the hostname should be set to your local IP, not a URL.</p><h3><strong>Reference</strong></h3><ul><li><a href="https://ithelp.ithome.com.tw/articles/10308906">[Day 30] Deployment - Fly.io 什麼的已經夠了啦。|【搜尋引擎製作錄】 - iT 邦幫忙::一起幫忙解決難題，拯救 IT 人的一天</a></li><li><a href="https://fly.io/docs/">Fly.io developer documentation</a></li><li><a href="https://learningsky.io/deploy-nodejs-express-app-to-flyio-cloud/">【 Cloud 】部署 Node.js Express App 到 Fly.io 雲端平台</a></li><li><a href="https://uu9924079.medium.com/fly-io-%E4%BD%BF%E7%94%A8%E5%BF%83%E5%BE%97-%E5%BE%9E%E8%A8%BB%E5%86%8A-%E4%BD%88%E7%BD%B2-nodejs-%E5%B0%88%E6%A1%88%E5%88%B0%E7%B6%B2%E5%9F%9F%E8%A8%AD%E5%AE%9A-2fee3b64fbe6">fly.io 使用心得，從註冊、佈署 NodeJS 專案到網域設定</a></li><li><a href="https://medium.com/@teppei.252033/%E7%94%A8-fly-io-%E9%83%A8%E7%BD%B2%E9%A4%90%E5%BB%B3%E8%AB%96%E5%A3%87-33c6562d6e09">用 fly.io 部署餐廳論壇</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d691afd5958" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[近一年的線上學習課程經驗(Alphacamp)]]></title>
            <link>https://medium.com/@wenliangsu65018/%E8%BF%91%E4%B8%80%E5%B9%B4%E7%9A%84%E7%B7%9A%E4%B8%8A%E5%AD%B8%E7%BF%92%E8%AA%B2%E7%A8%8B%E7%B6%93%E9%A9%97-alphacamp-367d5f7f081f?source=rss-9abbd74e1a5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/367d5f7f081f</guid>
            <dc:creator><![CDATA[Wen]]></dc:creator>
            <pubDate>Fri, 07 Apr 2023 14:31:39 GMT</pubDate>
            <atom:updated>2023-04-11T15:59:53.910Z</atom:updated>
            <content:encoded><![CDATA[<h3>近一年的線上學習課程經驗</h3><h4>Alphacamp線上課程完結</h4><p>年輕的時候轉職，可能沒什麼壓力，身上沒什麼包袱，可以無所畏懼地去做轉職的準備。年過30後，轉職的壓力開始油然而生，可能身邊開始有包袱要扛，有個小家庭要撐著，抑或著想要提升到管理職讓自己更上層樓。中年的轉職，尤其超過40後可以說是真的需要做好心理準備，需要考慮到很多的事情，有家庭又有小孩的情況下，若要採用全職學習，真的可以說是需要有相當大的勇氣跟決心。但是…… 我還是做了這個決定～</p><p>這個決定可說是要有非常大的覺悟，因為背負著這個家的經濟問題，以及受到旁人眼光的對待，心裡的煎熬可說是很艱辛。還好家人們可以諒解，了解到自己想要更上層樓，想要趁年老之前多學些技能。（當然薪水說不是考量的點那是不可能的）</p><p>程式語言，在我大學稍微接觸過一個學期後，在我心中點燃了那小小的興趣之火。在經歷過了多年的工作洗禮之後，這個念頭變成了我另一個人生目標。在這個日新月異的科技大爆炸時代，勢必要讀懂軟體才可以跟得上這個世界，讓自己不會落於人後。在經過幾番的研究各家的教學課程後，我選擇了Alphacamp，因為我知道自己會很容易陷入惰性狀態，而它提供了我班級進度制，讓我每個禮拜強迫自己要把作業交出去，才可以得到專業人士的批改與修正建議。</p><p>學習的過程中，從一開始不懂的如何寫軟體，何謂Javascript，HTML and CSS。一直到現在了解何謂資料庫的建構，SQL &amp; NoSQL, server建置，個人資料驗證的過程與機制。從最基礎的array操作，object &amp; constructor object 一直到 整個DOM的操作並連帶動HTML以及CSS。 此外，作業的撰寫過程，一開始總是心灰意冷，總是想要堅持自己寫出來，但是越到後面發現，軟體的世界是很廣大的，可以觀摩別人的做法，但是不是只單純的抄襲，還要必須了解到別人為何這樣寫，以及這樣的做法他的邏輯概念是什麼都要懂。否則就會變得像助教所說的，一個能力用十年，而應該要讓自己成為一年學十個能力的人才。</p><p>自學並採用線上課程的學習方式，可以說是需要有高度的自制力，因為一不小心很可能就念入的惰性大發的階段，造成後續學習的效率不彰，很快地就會放棄自己當初的目標。而我自己，採用的作法便是當作跟平常工作一樣，朝九晚五，晚上陪玩小孩之後，有餘力再多學習一些，但是強迫自己要12點睡覺。如此規律的生活下去，才不會讓自己為了全職學習而放下所有的心態逐漸攤軟掉。也因為這樣，才可以堅持到最後完成這整個課程的最後一份團隊合作的專案。這樣的過程，也已深深烙印在人生的過程中。但是……我知道這不是結束，後面還有很多需要學的語言、框架、以及資料庫的各種應用能在等著我，學無止境，活到老學到老，這便是我想要的…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=367d5f7f081f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Twitter專案協作經驗]]></title>
            <link>https://medium.com/@wenliangsu65018/simple-twitter%E5%B0%88%E6%A1%88%E5%8D%94%E4%BD%9C%E7%B6%93%E9%A9%97-758d2fd822cc?source=rss-9abbd74e1a5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/758d2fd822cc</guid>
            <dc:creator><![CDATA[Wen]]></dc:creator>
            <pubDate>Thu, 06 Apr 2023 06:41:42 GMT</pubDate>
            <atom:updated>2023-04-06T06:56:09.460Z</atom:updated>
            <content:encoded><![CDATA[<h4>開發過程的反思與檢討</h4><h4>Team members: Wen, Billy, Isis, Winnie</h4><h4>Front-end repo: <a href="https://github.com/billychen0894/simple-twitter-frontend">simple twitter front-end</a> (Billy, Winnie)</h4><h4>Back-end repo: <a href="https://github.com/wenliangsu/twitter-api-2023">simple twitter back-end </a>(Wen, Isis)</h4><h4>Deploy app: <a href="https://simple-twitter-frontend.vercel.app/login">simple twitter</a></h4><figure><img alt="Image" src="https://cdn-images-1.medium.com/max/1024/0*B9E16vKnQdBVvVmr.png" /></figure><p><strong><em>前言</em></strong></p><p>在撰寫code的時候不論是任何專案，其最重要的便是你的專案是否有跟人合作過。在個人專案中，也許自己寫的很順手，或是別人看你的code感覺你使用的技術特別的厲害，然而在合作專案中，即便寫得再酷再炫的技巧，要是別人看不懂或是讓專案出現了重大的bug需要進行修正，那也是一陣枉然。一個好的application需要的是各項功能執行的流暢，彼此功能的呼叫、Database的執行或是效能的差異都會影響到這個applicaton的使用者體驗。</p><p>再者，協作的過程中，彼此間的溝通是否有順暢，遇到狀況的排除以及互相的幫忙，這都是個人的 project中體驗不到的。而且，企業講求的是團隊合作，這一份專案可能會牽涉到好幾個人的考績，要是合作溝通困難的話，即便自己的技術在高深也是徒然的。</p><p><strong><em>專案前期</em></strong></p><p>在開發之前，最重要的是所需要的東西統一出來，例如Acceptance criteria(AC), Deification of done (DOD), back-end API 以及需送出的data structure. 此外，還有每個人的都coding style 以及其他的環境建置，例如passport 使用的authentication 機制為何，密碼採用hash的複雜度係數。這些都是需要去透過彼此間溝通後做定案。因此在第一次的meeting，所耗費的時間可以說是長達快一個晚上。尤其是為了訂出每一個細項的AC以及對於DOD所要達成的共識（即何謂所謂的這項工作是真正的Done)</p><figure><img alt="AC項目" src="https://cdn-images-1.medium.com/max/1024/0*WWAjxXm6SeuBuemK.png" /><figcaption>Acceptance Criteria項目</figcaption></figure><figure><img alt="Image" src="https://cdn-images-1.medium.com/max/1024/0*4SivFC7asI7ArVOV.png" /><figcaption>Definition of don 項目</figcaption></figure><figure><img alt="Image" src="https://cdn-images-1.medium.com/max/1024/0*Yvlp6TdSTnURRWCL.png" /><figcaption>Back-end API</figcaption></figure><p><strong><em>專案進行過程</em></strong></p><p>在撰寫code的時候不論是任何專案，其最重要的便是你的專案是否有跟人合作過。在個人專案中，也許自己寫的很順手，或是別人看你的code感覺你使用的技術特別的厲害，然而在合作專案中，即便寫得再酷再炫的技巧，要是別人看不懂或是讓專案出現了重大的bug需要進行修正，那也是一陣枉然。一個好的application需要的是各項功能執行的流暢，彼此功能的呼叫、Database的執行或是效能的差異都會影響到這個applicaton的使用者體驗。</p><p>協作的過程中，彼此間的溝通是否有順暢，遇到狀況的排除以及互相的幫忙，這都是個人的 project中體驗不到的。而且，企業講求的是團隊合作，這一份專案可能會牽涉到好幾個人的考績，要是合作溝通困難的話，即便自己的技術在高深也是徒然的。</p><figure><img alt="Image" src="https://cdn-images-1.medium.com/max/1024/0*G-HXlzux4LDq9zn1.png" /><figcaption>Task list of Back-end</figcaption></figure><p><strong><em>專案後期</em></strong></p><p>當後端的API撰寫完畢後，並測試完成無問題產生，則會開始與前端的部分進行串接，然而串接的過程上雖然解決了同源政策的問題，但是串接的資料格式上面卻產生了些許的落差，可能前端想要的資料內容在該頁要有account , name, avatar，但是後端給予的資料內容卻少了一個。因此必須要立即的處理並部署後，才可以讓前端繼續進行串接。然而本成員中有一位位於溫哥華，與其他三人的時間不同，因此在半夜上有時候緊急的話則需要立即在睡夢中起來處理，不過本團隊後端都能配合早上與該前端人員進行溝通，後續的資料格式修正或是需增加的API都可以得到迅速的改善。</p><p><strong><em>開發過程中的反思</em></strong></p><p>在這過程中，有個重大的問題在於，前端一個人因進度較快，另一個人的學習進度較慢，因此在這專案開始時，已經由此人建置完大部分的頁面，只剩下後台的部分給予另一個人建置。雖然看似進度很快，但是卻在後期串接的過程中發生嚴重的問題，致使讓另一位前端的人員幫不上忙，原因是這部分的code使用上只有他自己看得懂，反而讓另一個前端的人看不懂他的code而造成若是產生的bug必須由他來進行修補，而後端想要支援也無法支援，因這部分的難度牽涉到code的耦合性，這是一個其中的問題。</p><p>另一方面，在專案進行的初期並未明確建立組長或是PM角色，雖然本人有擔任過PM的經驗，但是為了讓大家都能學習PM的角色，讓其他組員接手這項任務，而本人給予從旁協助。然而，由於先前的問題，導致前端人員一個人負責大部分的debug, 而另一個前端人員則是建置進度較緩慢，因此原先擔任PM角色的前端人員便無暇去顧及文件的審查與更新，便由本人來接續這個角色的工作，並也開始隨時審查前端的作業進度，每當一功能完成時，便立即進行測試，立即核對AC以及DOD來確保可驗收。在全部的功能完成後，便可以針對先前審查完後的缺失，一並進行改善。</p><p><strong><em>結語</em></strong></p><p>在專案的最後，也如期的提交並驗收通過。這過程的學習經驗成果卻是豐碩的，在一個團隊下，每個人的角色都有其功能，但是最不能缺少的便是領頭的角色，例如PM或是組長。在缺少的情形下變的決策無法下定，一些事情會變得窒礙難行。雖然在專案開始的前期已經耗費較多時間的討論，然而若是沒有個決策者，則討論的再多終究會變成無結果論， 如此當碰到突發狀況的時候，便會變得手足無措。而前期的溝通甚為重要，因此對於之後的專案，如有其合作的夥伴，則會在溝通更多，讓彼此知道自身的需求與規格為何。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=758d2fd822cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Catching Errors in Javascript]]></title>
            <link>https://medium.com/@wenliangsu65018/catching-errors-in-javascript-c90326e0d6b?source=rss-9abbd74e1a5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c90326e0d6b</guid>
            <dc:creator><![CDATA[Wen]]></dc:creator>
            <pubDate>Wed, 01 Mar 2023 09:10:34 GMT</pubDate>
            <atom:updated>2023-03-01T09:37:37.046Z</atom:updated>
            <content:encoded><![CDATA[<p>It is normal situation when you write the code and no one can make it perfectly. So, Error must be happened. However, we have to know how to catch the error and where is the error?</p><h4>When does it happen?</h4><p>In Javascript(JS), we can classify it into two classes:</p><ol><li>Programing error: <br> For example, the syntax error, typer error or some variables are undefined, etc..</li><li>Operational error: <br> This error is from the system, like the fail from reading file, or connection is unusual, etc..</li></ol><h4>Error object in JS</h4><p>In MDN, there are six types of error as following:</p><ol><li>Eval Error: It occurs regrading the global function eval().</li><li>Range Error: It occurs when numeric variable or parameter is out of range.</li><li>Syntax Error: It occurs when writing the wrong syntax in your code.</li><li>Reference Error: You take the invalid ref</li><li>Type Error: The variable or parameter is not of a valid type.</li><li>URI Error: Pass the wrong parameter when using the method of encodeURI() or decodeUR().</li></ol><p>So, it has an error object in JS to deal with these error types. And we can use this object to create an instance to catch a generic error by following:</p><pre>try {<br>  throw new Error(&quot;Whoops!&quot;);<br>} catch (e) {<br>  console.error(`${e.name}: ${e.message}`);<br>}</pre><h3>Error handle in asynchrony</h3><p>As an example from above, it use to catch by the synchronous function. if we write the asynchronous function, it will have no effect.</p><pre>try {<br>  setTimeout(() =&gt; {<br>    throw new Error(&#39;asyncError&#39;);<br>  }, 0)<br>} catch(err) {<br>  console.log(err);<br>}<br><br>// Uncaught Error: asyncError</pre><p>The asynchronous operation is implemented by even-loop mechanism. It means that the stack already has been executed when the callback function in the event queue is executed. So, we have to use other methods to catch it.</p><h4>Error-first-callback</h4><p>We can set the first parameter to the error object in the callback function as following:</p><pre>router.get(&#39;/signin&#39;, (err, req, res) =&gt; {<br>  if (err) {<br>     console.log(err)<br>  }<br>})</pre><h4>Error in promise</h4><p>With advent of the Promise standard, it provided the handling method Promise.prototype.catch for error object.</p><pre>User.findOne({ where: { email: req.body.email } })<br>      .then(user =&gt; {<br>        if (user) throw new Error(&#39;Email already exists!&#39;);<br>        ...<br>      })<br>      .then(hash =&gt;<br>        User.create({<br>         ...<br>        })<br>      )<br>      .then(() =&gt; {<br>        ...<br>      })<br>      .catch(err =&gt; next(err))</pre><h4>async/await</h4><p>It show at ES7 and can write as following:</p><pre>async function test() {<br>  try {<br>    await fetch(&#39;http://www.google.com&#39;);<br>  }catch(err) {<br>    console.log(err);<br>  }<br>}<br><br>test();</pre><p>it is better to use the async//await when we use the try…catch… to catch the error. Async/await is a syntax sugar for Promise. So it also can be converted to the Promise syntax.</p><h3>Handling the different kind of errors</h3><p>When we get some different kind of requests and we use try .. catch.. to catch these errors, maybe we can write as following:</p><pre>try {<br>  await request1()<br>  await request2()<br>  await request3()<br>} catch (err) {<br>  // error handling<br>}</pre><p>When error happened, we don’t know which request occur that. In order to identify it, we can refactor the code as following of two methods:</p><p>(1)</p><pre>async function test(){<br>  try {<br>    await request1()<br>  } catch(err1) {<br>    // Handling err1 <br>  }<br>  <br>  try {<br>    await request2()<br>  } catch(err2) {<br>    // Handling err2 <br>  }<br>  <br>  try {<br>    await request3()<br>  } catch(err3) {<br>    // Handling err3 <br>  }<br>}</pre><p>(2)</p><pre>try {<br>  await request1() // throw Error1<br>  await request2() // throw Error2<br>  await request3() // throw Error3<br>} catch (err) {<br>  if (err instanceof Error1) {<br>    // Handling the error1<br>  } else if (err instanceof Error2) {<br>    // Handling the error2<br>  } else if (err instanceof Error3) {<br>    // Handling the error3<br>  } else {<br>    // Handling other error<br>  }<br>}</pre><p>However, it is unreadability in method(1) when the code is getting longer and longer. Then, you have to customize your error and analyze the code of error at the request in method (2). It will take your time to read all of the customized error.</p><h3>The different way for error handling</h3><p>Fortunately, some people find the solution when they write the Go-Lang and find how did they handle the error.</p><p>(ref: <a href="https://blog.grossman.io/how-to-write-async-await-without-try-catch-blocks-in-javascript/">How to write async/ await without try-catch blocks in JS</a>)</p><pre>data, err := db.Query(&quot;SELECT ...&quot;)<br>if err != nil { return err }</pre><p>So we can write as following if it is used in Node.js.</p><pre>async request1() {<br>    try {<br>        // request1 process<br>        return [result1, null]<br>    } catch (err1) {<br>        // err1 handling<br>        return [null, Error1]<br>    }<br>}<br><br>async request2() {<br>    try {<br>        // request2 process<br>        return [result2, null]<br>    } catch (err2) {<br>        // err2 handling<br>        return [null, Error2]<br>    }<br>}<br><br>const [result1, Error1] ＝ await request1()<br>if (Error1) {<br>  // Error1 handling<br>}<br><br>const [result2, Error2] ＝ await request2()<br>if (Error2) {<br>  // Error2 handling<br>}</pre><p>The reason of refactoring this code is according to that **await **is waiting on a promise to resolve. And the request can be a promise object. So, this <a href="https://blog.grossman.io/how-to-write-async-await-without-try-catch-blocks-in-javascript/">author</a> make a small utility function to help to catch the errors as following:</p><p>(ref: <a href="https://blog.grossman.io/how-to-write-async-await-without-try-catch-blocks-in-javascript/">How to write async/ await without try-catch blocks in JS</a>,<a href="https://github.com/scopsy/await-to-js"> npm package: await-to-js</a>)</p><pre>// to.js<br>export default function to(promise) {<br>   return promise.then(data =&gt; {<br>      return [null, data];<br>   })<br>   .catch(err =&gt; [err]);<br>}</pre><p>While we have this concept, we can refactor the code as following after install <a href="https://github.com/scopsy/await-to-js?ref=codebits">await-to-js</a> which the author developed. Now, we don’t need to write the async function and make them clearly.</p><pre>import to from &#39;await-to-js&#39;;<br><br>const [result1, Error1] ＝ await to(request1())<br>if (Error1) {<br>  // Error1 handling<br>}<br><br>const [result2, Error2] ＝ await to(request2())<br>if (Error2) {<br>  // Error2 handling<br>}<br><br>const [result3, Error3] ＝ await to(request3())<br>if (Error3) {<br>  // Error3 handling<br>}</pre><h4>Conclusion</h4><p>Error handling is an important thing of development. We have to know what kind of error will be occurred or how to catch them. By using error object and customizing the error with Promise, async/await, it helps us to check the error during developing. It is hard to write a well or clean code for error handling even by using the Promise, async/await. However, it is necessary to learn this knowledge and understand the concept of error handling. Now people try to find the solution to make the code to be more readable, like the package of await-to-js. Therefore, keeping learning the basic concept of technique and improving the code are very important.</p><p><strong>Reference:</strong></p><ul><li><a href="https://blog.grossman.io/how-to-write-async-await-without-try-catch-blocks-in-javascript/">How to write async await without try-catch blocks in Javascript</a></li><li><a href="https://engineering.udacity.com/handling-errors-like-a-pro-in-typescript-d7a314ad4991">Handling errors like a pro in TypeScript</a></li><li><a href="https://eyesofkids.gitbooks.io/javascript-start-from-es6/content/part3/error.html">錯誤與例外處理</a></li><li><a href="https://ithelp.ithome.com.tw/articles/10230537">Week6 - 原來我Server錯誤處理本身的方案就是個錯誤(/ﾟДﾟ)/ - 錯誤處理篇 [NodeJs轉Golang的爆炸之旅系列] - iT 邦幫忙::一起幫忙解決難題，拯救 IT 人的一天</a></li><li><a href="https://pjchender.blogspot.com/2017/12/js-error-handling.html">[JS] 談談 JavaScript 中的錯誤處理 Error Handling</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#exception_handling_statements">Control flow and error handling - JavaScript | MDN</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error">Error - JavaScript | MDN</a></li><li><a href="https://ithelp.ithome.com.tw/articles/10241761">[今晚我想來點 Express 佐 MVC 分層架構] DAY 07 - Express 錯誤處理 - iT 邦幫忙::一起幫忙解決難題，拯救 IT 人的一天</a></li><li><a href="https://mainpage.github.io/2020/07/05/error-and-exception/">聊聊nodejs的错误处理</a></li><li><a href="https://blog.csdn.net/pfourfire/article/details/124794091">await-to-js ：22 行代码让你摆脱 async、await 中繁琐的 try、catch_姑老爷呀的博客-CSDN博客</a></li><li><a href="https://www.casper.tw/development/2021/09/14/js-console/">JavaScript Console 運用技巧 - 8 招讓你除錯更高效</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c90326e0d6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Expense-tracker project]]></title>
            <link>https://medium.com/@wenliangsu65018/expense-tracker-project-bc71aceb82b3?source=rss-9abbd74e1a5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc71aceb82b3</guid>
            <dc:creator><![CDATA[Wen]]></dc:creator>
            <pubDate>Tue, 14 Feb 2023 03:43:51 GMT</pubDate>
            <atom:updated>2023-02-14T03:49:26.203Z</atom:updated>
            <content:encoded><![CDATA[<h4>The record for using the express, node.js and MongoDB</h4><h3><strong>Introduction</strong></h3><p>I am a newbie for learning the program language of JS (javascript), HTML, CSS. We know that everyone make the Todo-list project when they were also newbies, and me too. After learning the make the todo-list project by Express and Node.js, using the database by MangoDB and SQL. I want to enhance my memory and keep to use the technique what I just learn. So, this project need to have some features:</p><ul><li>It doesn’t cost me more then two week.</li><li>Can use simple template to produce the web page. (Cause I want to learn the Back-end system)</li><li>Can operate the database and easy to use a lot of different syntax in the same logical function.</li><li>In future, I can extend more feature if I finish it.(like the analysis, figure, connection of other cloud storage)</li></ul><p>The expense-tracker can be matched with above that why I choose it.</p><h3>Technique aspect</h3><p>For the code environment, I use these package of technique as following:</p><ol><li>Node.js &amp; express: that is the base environment for back-end system. Express is much light package for setting up the serve and Node.js can help me to write the JS code on my terminal. Of course, it has handlebar and session in Express that I don’t need to download other package.</li><li>MongoDB: it is a NoSQL database. For this project, it doesn’t need to have many table to take the relationship with each. Just use the simple data, like the categories, users and expense’s record. Only three tables can connect together. For SQL, I consider it can be used for the complicated tables, like the record of food or sweet recipe because it needs comment, materials, food style , etc..</li><li>Passport for local, FB &amp; Google: it is very important to verify the user by the verification of package. Passport can do it easily and it is always used with Node and Express.</li><li>MVC model: I use this model to design process of programing because it will be add the expansion of features in and modify the code easily in future. For example, if you want to add some feature, you can add the the function of code in the controller and set the route in the modules.</li></ol><h3>The Challenge</h3><p>In this project, there are some challenges that I meet as following:</p><ul><li>First, it cost me a lot of time to consider the configuration of folders and the structure of MVC. Like what kind of files should be put in the models, and what kind of controllers should I do. I tried to write the routes of all features that can make me to think easily. After writing the routes, I start to follow the step of MVC model so that can make me work fluently.</li><li>M: create or modify the database models.</li><li>V: write the view page of the feature by HTML.</li><li>C: write the logical program for this feature in the controller folder.</li><li>It also consume a lot of time by searching the technical document for the syntax. Sometime, you may have some errors or bugs when implementing the code and need to fix them, or you try to add the new feature that you had never made it. The way for solution maybe is by google the problem, watch the official document. However, the important point is you need to type the point of keyword. It will not help you to solve the problem fast if you type the wrong the keyword.</li><li>Some problems are about the order for implementing the program. For example, you want to edit the expense and update it in the database and show it on the page but it didn’t work even it didn’t show the error for you and everything looks normal. You have to think about the order of program execution clearly or it will take you a lot of time to fix that.</li></ul><h3>Conclusion</h3><p>It very important to think the design of route, database or the configuration of MVC model before starting to code that. You will make the project very fluently if you prepare everything well and can reduce the layers of error.</p><p><a href="https://github.com/wenliangsu/expense-tracker-mongoDB">GitHub: Expense-tracker</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc71aceb82b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asynchronous (Callback, Promise, async/await)]]></title>
            <link>https://medium.com/@wenliangsu65018/asynchronous-callback-promise-async-await-614399fc5152?source=rss-9abbd74e1a5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/614399fc5152</guid>
            <dc:creator><![CDATA[Wen]]></dc:creator>
            <pubDate>Mon, 26 Dec 2022 05:32:09 GMT</pubDate>
            <atom:updated>2022-12-26T05:47:36.713Z</atom:updated>
            <content:encoded><![CDATA[<p>In generally, we understand what are synchronous and asynchronous meaning. However, for asynchronous, we don’t understand how to use these function to deal it even we know the meaning. This is a purpose for using the simple sentence to make newbie to understand.</p><h3>callback()</h3><p>The normal callback function for simple example is as following. We use delayFunc() to be a parameter and put into the mainFunc(). The mainFunc() will implement in order. So the output is show in the code block.</p><pre>function delayFunc() {<br>  console.log(&#39;This delay function is done.&#39;);<br>}<br>function mainFunc(callback) {<br>  console.log(&#39;This is main start.&#39;);<br>  callback();<br>  console.log(&#39;This is main end.&#39;);<br>}<br><br>mainFunc(delayFunc);<br><br>/* output :<br>This is main start.<br>This delay function is done.<br>This is main end.*/</pre><p>We assume the delayFunc1(), delayFunc(2) anddelayFunc(3) are asynchronous functions and need the time to finish. The example is as following. In mainFunc(), you can see we set the function as a nest so that the mainFunc()can implement in order.(delayFunc1 ⇒ delayFunc2 ⇒ delayFunc3)</p><pre>function delayFunc1(callback) {<br>  setTimeout(() =&gt; {<br>    console.log(&#39;delayFunc1 is done&#39;);<br>    callback();<br>  }, 3000);<br>}<br>function delayFunc2(callback) {<br>  setTimeout(() =&gt; {<br>    console.log(&#39;delayFunc2 is done&#39;);<br>    callback();<br>  }, 2000);<br>}<br><br>function delayFunc3(callback) {<br>  setTimeout(() =&gt; {<br>    console.log(&#39;delayFunc3 is done&#39;);<br>    callback();<br>  }, 1000);<br>}<br><br>function mainFunc(callback) {<br>  delayFunc1(() =&gt; {<br>    delayFunc2(() =&gt; {<br>      delayFunc3(() =&gt; {<br>        callback();<br>      });<br>    });<br>  });<br>}<br>mainFunc(() =&gt; {<br>  console.log(&#39;All function is done.&#39;);<br>});<br><br>/* delayFunc1 is done<br>delayFunc2 is done<br>delayFunc3 is done<br>All function is done.*/</pre><p>However, it is hard to review these code if the nest becomes more complication. So, we use promise function to improve it.</p><h3>Promise</h3><p>Promise can allows you to associate handlers with asychronous action&#39;s eventual success value or failure reason. There are three states in Promise :</p><ol><li>pending: initial state, means it is not finish treatment.</li><li>resolve: it means success and finish the implement.</li><li>reject: something is failure or error is occurred.</li></ol><pre>//Instance<br>new Promise((resolve, reject) =&gt; {})</pre><p>When using the Promise, you have to create the instance first via new Promise() and set a argument for this instance that can use the it to control the process by .then(). There is a simple example as following:</p><pre>var error = false;<br>var promiseInstance = new Promise((resolve, reject) =&gt; {<br>  setTimeout(() =&gt; {<br>    if (error) {   <br>      return reject(&#39;error happen&#39;);<br>    }<br><br>    console.log(&#39;Work(1) is done&#39;);<br>    resolve(); //Can return value or object, ex. resolve(1)<br>  }, 3000);<br>});<br><br>promiseInstance<br>  .then(() =&gt; {<br>    console.log(&#39;Work(2) is done&#39;);<br>  })<br>  .then(() =&gt; {<br>    console.log(&#39;All works is done&#39;);<br>  })<br>  .catch((error) =&gt; {<br>    console.warn(error);<br>  });<br><br>/* Work(1) is done<br>   Work(2) is done<br>   All works is done */</pre><p>Explanation:</p><p>First, we set a new instance of PromiseInstance and include the asynchronous process that need 3 seconds to display the result. Then, PromiseInstance.then(…) can implement the next work or catch the error and so on. When using resolve() , Promise state is success and can return the object or value. And it will be transfer to the next process to utilize. However, it will be no longer to implement`.then() if Promise get the reject() and error is occurred that will go to.catch() to display the error message.</p><p>However, we may have two or three function are asynchronous and want to execute in order. You need to make another promise instance to insert one of .then() like the example as following. So, it can display in order. The example is as following:</p><pre>var error = false;<br>var promiseInstance = new Promise((resolve, reject) =&gt; {<br>  setTimeout(() =&gt; {<br>    if (error) {<br>      return reject(&#39;error happen&#39;);<br>    }<br><br>    console.log(&#39;Work(1) is done&#39;);<br>    resolve();<br>  }, 3000);<br>});<br><br>promiseInstance<br>  .then(() =&gt; {<br>    console.log(&#39;Work(2) is done&#39;);<br>  })<br>  .then(() =&gt; {<br>    return new Promise((resolve, reject) =&gt; {<br>      setTimeout(() =&gt; {<br>        console.log(&#39;Work(3) is done&#39;);<br>        resolve();<br>      }, 3000);<br>    });<br>  })<br>  .then(() =&gt; {<br>    console.log(&#39;All works is done&#39;);<br>  })<br>  .catch((error) =&gt; {<br>    console.warn(error);<br>    console.log(promiseInstance);<br>  });<br><br>/* Work(1) is done<br>   Work(2) is done<br>   Work(3) is done<br>   All works is done */</pre><h4><strong>Promise.all()</strong></h4><p>In generally, you have a lot of asynchronous function need to execute and could set a lot of promise. Promise.all() can confirm that all of them are executed and go .then() to finish this code. The example is as following:</p><pre>var error = false;<br>var promiseInstance1 = new Promise((resolve, reject) =&gt; {<br>  setTimeout(() =&gt; {<br>    if (error) {<br>      reject(&#39;error happen(1)&#39;);<br>    }<br><br>    console.log(&#39;Work(1) is done&#39;);<br>    resolve();<br>  }, 3000);<br>});<br><br>var promiseInstance2 = new Promise((resolve, reject) =&gt; {<br>  setTimeout(() =&gt; {<br>    if (error) {<br>      reject(&#39;error happen(2)&#39;);<br>    }<br>    console.log(&#39;Work(2) is done&#39;);<br>    resolve();<br>  }, 1000);<br>});<br><br>Promise.all([promiseInstance1, promiseInstance2])<br>  .then(() =&gt; {<br>    console.log(&#39;Work(3) is done&#39;);<br>  })<br>  .then(() =&gt; {<br>    console.log(&#39;All works is done&#39;);<br>  })<br>  .catch((error) =&gt; {<br>    console.warn(error);<br>  });<br><br>/* Work(2) is done<br>   Work(1) is done<br>   Work(3) is done<br>   All works is done */</pre><p>However, you can see the results are not in order. Promise.all() just make sure that it execute all of them but not keeping them in order. So, you have to write some code to fix them (it&#39;s not the purpose of this article for deeply research). The figure shows about the process of Promise.all().</p><figure><img alt="Image" src="https://cdn-images-1.medium.com/max/1024/0*F4hjN0AiMmQl_fCx.png" /></figure><h3>async/await</h3><p>async/await is just a syntax sugar because it includes the syntax of Promise. First, you have to know if this function includes the Promise or not and then you can use async/await. Then, declare the function is a async function as following example and write the await before the asynchronous function. When main() execute, it will wait the asynchronous function to finish and then go to the next. This syntax is contained the concept of Promise. You need to learn the Promise first before utilizing this syntax.</p><p>There is one thing you have to know about the error message. You have to use the try {…} catch {…} to get error message cause it is included in Promise and use .catch() to get the error. And you need to write the catch inside the async function or it will not get the message if you write it outside.</p><pre>var error = false;<br>function promiseInstance1() {<br>  return new Promise((resolve, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>      if (error) {<br>        reject(&#39;error happen(1)&#39;);<br>      }<br>      console.log(&#39;Work(1) is done&#39;);<br>      resolve();<br>    }, 3000);<br>  });<br>}<br><br>function promiseInstance2() {<br>  return new Promise((resolve, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>      if (error) {<br>        reject(&#39;error happen(2)&#39;);<br>      }<br>      console.log(&#39;Work(2) is done&#39;);<br>      resolve();<br>    }, 1000);<br>  });<br>}<br><br><br>async function main() {<br>  try {<br>    await promiseInstance1();<br>    await promiseInstance2();<br><br>    console.log(&#39;Work(3) is done&#39;);<br>    console.log(&#39;All works is done&#39;);<br>  } catch {<br>    console.log(&#39;error&#39;);<br>  }<br>}<br><br>main();<br><br>/* Work(1) is done<br>   Work(2) is done<br>   Work(3) is done<br>   All works is done */</pre><p>(Please leave a message to me if there are some wrong concepts of this article.)</p><p>Ref:</p><p><a href="https://www.freecodecamp.org/news/asynchronous-javascript-explained/">Asynchronous JavaScript — Callbacks, Promises, and Async/Await Explained</a></p><p><a href="https://medium.com/@yining1204/javascript%E4%B8%AD%E7%9A%84%E9%9D%9E%E5%90%8C%E6%AD%A5%E8%99%95%E7%90%86%E6%A9%9F%E5%88%B6-promise-9b7c87603e47">JavaScript中的非同步處理機制 — Promise</a></p><p><a href="https://yu-jack.github.io/2018/07/22/promise/">callback, promise, async/await 使用方式教學以及介紹 Part I</a></p><p><a href="https://ithelp.ithome.com.tw/articles/10275947">Day 16 — Asynchronous 非同步進化順序 — Async/Await — iT 邦幫忙::一起幫忙解決難題，拯救 IT 人的一天</a></p><p><a href="https://ithelp.ithome.com.tw/articles/10298979?sc=iThelpR">JS之路 Day11 — Callback Funtion(回呼函式) — iT 邦幫忙::一起幫忙解決難題，拯救 IT 人的一天</a></p><p><a href="https://eyesofkids.gitbooks.io/javascript-start-es6-promise/content/contents/ch3_promise_a_plus.html">Promises/A+標準定義 · 從Promise開始的JavaScript異步生活</a></p><p><a href="https://yu-jack.github.io/2019/05/02/promise-2/">callback, promise, async/await 使用方式教學以及介紹 Part II (Error Handling 介紹)</a></p><p><a href="https://cnodejs.org/topic/5c0ddfbe7ec239239ff5533a">8张图让你一步步看清 async/await 和 promise 的执行顺序 — CNode技术社区</a></p><p><a href="https://segmentfault.com/a/1190000040514839">前端 — 技术篇 — 如何使用 Promise.all() — 个人文章 — SegmentFault 思否</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=614399fc5152" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cookie and Session]]></title>
            <link>https://medium.com/@wenliangsu65018/cookie-and-session-7d3e2438572a?source=rss-9abbd74e1a5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d3e2438572a</guid>
            <dc:creator><![CDATA[Wen]]></dc:creator>
            <pubDate>Mon, 05 Dec 2022 09:27:22 GMT</pubDate>
            <atom:updated>2022-12-05T09:30:13.905Z</atom:updated>
            <content:encoded><![CDATA[<h4>HTTP stateless</h4><p>To talk this subject, we have to know what is the stateless protocol in HTTP. The stateless protocol means that when the computers communicate with each other, they don’t care their state and all the requests are independent. Their results or records are not store in the browser. So, you have to send the same information to the other computer when you visit the other website and come back the original one, just like the account you have to login again.</p><h4>Cookie</h4><p>Cookie is a part of information that the client side got from the server side and store in the browser. When you visit the same website again, the client side doesn’t need to send the request to get the info from the server. For example, the shop website can know what you put put inside in your cart cause these info were already store in the cookie. it just take out it and render this page to show you.However, cookie is a small text file that save it on user’s computer. So it will be easily to be modified by the third-part software.</p><p>For operating the cookie, we can install the cookie-parser first (if your project is build in Express)</p><p>npm i cookie-parser</p><p>then, run the code as following:</p><pre>const express = require(&#39;express&#39;)<br>const cookie = require(&quot;cookie-parser&quot;)<br><br>const app = express()<br><br>app.use(cookie())<br><br>cookie(secret, {<br> path: &#39;/&#39;<br> maxAge: 6000<br> secure: true<br> httpOnly: true<br>})</pre><p>Secret can encrypt the cookie and the option can be :</p><ol><li>path: the cookie can affect the path</li><li>maxAge: how long the cookie will be delete in seconds</li><li>secure: if it is true, it will send by https.</li><li>httpOnly: the browser cannot allow the code to modify the cookie</li></ol><h4>Session</h4><p>Session can save this part of information into the server. it will give a hash value to encrypt the info (sessionID) and then cookie receive it and set in the browser. So it is more safety to store the private info on the client side and these operation are on the server side cause the third-party software only get the encrypted value and can pass by comparing it on the server.</p><p>The framework of express give the middleware to operate the cookie. it need to install the express-session at first:</p><p>npm i express-session</p><p>then, you can run the code as following:</p><pre>const express = require(&quot;express&quot;);<br><br>const session = require(&quot;express-session&quot;)<br><br>const app = express();<br><br>//session(options)<br><br>app.use(session({<br>  secret: &#39;This a secret test for Wen&#39;, <br>  resave: false,<br>  saveUninitialized: false,<br>  cookie : {maxAge: 60000, httpOnly: true}<br>}))</pre><p>It has a lot of <a href="https://www.npmjs.com/package/express-session">options </a>to choose. the importants are as following:</p><ol><li>name: the default is connect.sid but we can customize .</li><li>genid: it is a function to call to generate a new session ID.</li><li>rolling: the default is false. Each request need to create a cookie.</li><li>resave: it will save the session even if it is not to be modified.</li><li>saveUninitialized: force to initialize the new session. The default is false.</li><li>secret: it is required option !! It is used to sign the sessionID cookie by hash value. (of cause, you can encrypt by self)</li><li>cookie: you can operate the option of cookie.</li></ol><p>Ref:</p><p><a href="https://ithelp.ithome.com.tw/articles/10187212">Day23 — Cookie &amp; Session — iT 邦幫忙::一起幫忙解決難題，拯救 IT 人的一天</a></p><p><a href="https://blog.hellojcc.tw/introduce-session-and-cookie/">介紹 Session 及 Cookie 兩者的差別說明</a></p><p><a href="https://www.npmjs.com/package/express-session">express-session</a></p><p><a href="https://blog.csdn.net/antony1776/article/details/83474496">深入理解无状态协议、HTTP 与 web 会话_墨城之左的博客-CSDN博客</a></p><p><a href="https://www.itread01.com/article/1517291126.html">express如何使用session與cookie的方法 — IT閱讀</a></p><p><a href="https://www.quora.com/What-does-it-mean-that-%E2%80%98HTTP-is-stateless%E2%80%99">What does it mean that ‘HTTP is stateless’? — Quora</a></p><p><a href="https://www.geeksforgeeks.org/difference-between-session-and-cookies/">Difference between Session and Cookies — GeeksforGeeks</a></p><p><a href="https://blog.techbridge.cc/2019/09/07/session-and-cookie-implementation/">深入 Session 與 Cookie：Express、PHP 與 Rails 的實作</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d3e2438572a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Copy the text to clipboard by JS and HTML]]></title>
            <link>https://medium.com/@wenliangsu65018/copy-the-text-to-clipboard-by-js-and-html-a6b0b2e42b5?source=rss-9abbd74e1a5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6b0b2e42b5</guid>
            <dc:creator><![CDATA[Wen]]></dc:creator>
            <pubDate>Thu, 01 Dec 2022 02:43:50 GMT</pubDate>
            <atom:updated>2022-12-22T12:24:22.692Z</atom:updated>
            <content:encoded><![CDATA[<p>How to copy text to clipboard ? there is a part of example about the shorten the URL as following:</p><p>Example HTML</p><pre>&lt;div class=&quot;container mt-2&quot; style=&quot;width: 400px;&quot;&gt;<br>  &lt;div class=&quot;row mt-2 justify-content-center&quot;&gt;<br>    &lt;h3 class=&quot;mb-1&quot;&gt;Success! PLease use this link:&lt;/h3&gt;<br>    &lt;input class=&quot;text-center mt-2&quot; id=&quot;shorten-url&quot; value=&quot;{{shortenUrl}}&quot; disabled&gt;<br>    &lt;div class=&quot;row justify-content-center&quot; id=&quot;btn-group&quot;&gt;<br>      &lt;button type=&quot;submit&quot; style=&quot;width: 100px;&quot; class=&quot;btn btn-success mt-4&quot; id=&quot;copy-button&quot; onclick=&quot;copyText()&quot;&gt;<br>        Copy to clipboard&lt;/button&gt;<br>      &lt;a href=&quot;/&quot; class=&quot;btn btn-primary ms-3 mt-4 pt-3&quot; style=&quot;width: 100px;&quot;&gt;Back&lt;/a&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p>Example JS</p><pre>&lt;script&gt;<br>    function copyText() {<br>      let copyInput = document.getElementById(&#39;shorten-url&#39;)<br>      let copied = document.getElementById(&#39;btn-group&#39;)<br>    <br>      copyInput.select()<br><br>      navigator.clipboard.writeText(copyInput.value)<br>      copied.innerHTML = `<br>      &lt;button type=&quot;submit&quot; style=&quot;width: 100px;&quot; class=&quot;btn btn-danger mt-4&quot; id=&quot;copy-button&quot; onclick=&quot;copyText()&quot;&gt;<br>        Already copied&lt;/button&gt;<br>      &lt;a href=&quot;/&quot; class=&quot;btn btn-primary ms-3 mt-4 pt-3&quot; style=&quot;width: 100px;&quot;&gt;Back&lt;/a&gt;<br>      `<br>    }<br>  &lt;/script&gt;</pre><p>In early, developer used the<a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand">execCommond()</a> to make this feature. Here is the explanation from MDN:</p><blockquote><strong>Deprecated:</strong> This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.</blockquote><p>According the W3school, I use the writeText() to do it. First, make a &lt;button&gt; with onclick event and write a function in&lt;script&gt;. To get the value of &lt;input&gt;, i use the select()to get all the content. Then, navigator.clipboard.writeText() will put it in the clipboard.</p><p>However, there is one thing have to pay attention. If you want to use alert(), it will have error cause the clipboard API is asynchronous. it will show the window of alert before finishing the copy process and error will show that:</p><p>Uncaught (in promise) DOMException: Document is not focused.</p><p>You have to use async/await to finish the process of clipboard then show the alert. The example is as following:</p><pre>&lt;script&gt;<br>    async function copyText() {<br>      let copyInput = document.getElementById(&#39;shorten-url&#39;)<br>      let copied = document.getElementById(&#39;btn-group&#39;)<br>    <br>      copyInput.select()<br><br>      await navigator.clipboard.writeText(copyInput.value)<br><br>      copied.innerHTML = `<br>      &lt;button type=&quot;submit&quot; style=&quot;width: 100px;&quot; class=&quot;btn btn-danger mt-4&quot; id=&quot;copy-button&quot; onclick=&quot;copyText()&quot;&gt;<br>        Already copied&lt;/button&gt;<br>      &lt;a href=&quot;/&quot; class=&quot;btn btn-primary ms-3 mt-4 pt-3&quot; style=&quot;width: 100px;&quot;&gt;Back&lt;/a&gt;<br>      `<br>    }<br>  &lt;/script&gt;</pre><p>Ref:</p><p><a href="https://web.dev/i18n/en/async-clipboard/">Unblocking clipboard access</a></p><p><a href="https://lichi-chen.medium.com/%E4%BD%BF%E7%94%A8-js-%E8%A4%87%E8%A3%BD%E8%B2%BC%E4%B8%8A%E5%89%AA%E8%B2%BC%E7%B0%BF%E7%99%BC%E7%94%9F-uncaught-in-promise-domexception-document-is-not-focused-e43b24362a82">使用 js 複製貼上剪貼簿發生 Uncaught (in promise) DOMException: Document is not focused.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6b0b2e42b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[自學經驗(半年學習期間)]]></title>
            <link>https://medium.com/@wenliangsu65018/%E8%87%AA%E5%AD%B8%E7%B6%93%E9%A9%97-%E5%8D%8A%E5%B9%B4%E5%AD%B8%E7%BF%92%E6%9C%9F%E9%96%93-eb31a03cc8c9?source=rss-9abbd74e1a5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb31a03cc8c9</guid>
            <dc:creator><![CDATA[Wen]]></dc:creator>
            <pubDate>Tue, 22 Nov 2022 09:05:20 GMT</pubDate>
            <atom:updated>2022-11-22T09:05:20.962Z</atom:updated>
            <content:encoded><![CDATA[<p>在進行最愛餐廳清單的專案撰寫過程中，有個要求是需要增加搜尋功能與排序的部分。對於使用mongoDB的資料搜尋文件，官方上面都寫得還算好。不過有時候變數他的設定讓人寫的看不太懂。</p><p>當然在寫的過程中，其實很沒有頭緒，搜尋功能上還可以看一下之前寫電影清單的時候，再稍微思考一下程式執行的情況後，就可以寫的出來。但是排序的部分則較沒有辦法。不過還好之前也有上過密碼產生器的時候，使用HTML來建立下拉式選單並透過JS來取value達成。</p><p>但是排序的JS寫法反而想了比較久一點。一開始寫的時候怎樣都取不到使用者選擇的選項，以為自己是不是找錯地方抓取value，便試了req.params, req.bod, req.query 來去看問題點。結果還是都沒抓到值，便去看一下W3School 以及MDN的文件，看針對input的部分是否我哪裡有疏忽的地方。</p><p>然而兩小時過去了，我還是找不到問題點在哪邊，這時便去看一下同學的寫法，或是Model answer的寫法。然後在進行嘗試用他們的做法去試試。因同學的寫法較特殊，也順便學習一下看他怎麼寫。但是在試驗過2個小時後，還是無法讀取到我想要的value。便開始去google問題點在哪邊以及去stockoverflow尋找解答。</p><p>在找的過程中，反而學到了一些取值的方式，以及大家的在寫的過程中遇到的問題點為何。當然我也把我自己遇到的問題也放在讀書會的群組中以及stackoverflow中，自己覺得一直解不出來的，就乾脆來發問看看，stackoverflow裡的人有回答，但是認為我這樣寫應該是沒錯誤。而群組的人也提了一些意見給我試試。</p><p>然而問題點還是沒找到也沒解決。就在這時群組同學給了我一個關鍵的思考方式。認為我是不是在HTML裡面把button tag 改成input tag。這時候腦袋突然靈光一閃，會不會我整個HTML的架構有錯誤。因此在重新檢視了架構後，發現到我把form tag又多包了一個form tag在裡面，難怪在跑的時候整個完全取值不到。只是一個小失誤卻是影響了快一整天的時間。當然也很謝謝那時候幫忙的人所提供的意見。</p><p>至於這過程中的收穫，可以說是學到很多一些額外的技術名詞定義以及寫法。雖然那是額外的，但是還是要控制自己不可以整個潛入太深層，不然會整個沒完沒了。好在大腦還有在理性運作，不然會搞個一個星期還沒研究出來。其實不是不想學習新知，而是當需要用到的時候，再來學習再來筆記，這樣才會因為一個問題點，而犧牲掉大半個時間，只為了一個問題在這。跟工作都很像，碰到問題，一時沒法解決，但是又不會影響整體運作的時候，就先行擱置。整其他的工作做完後再來回頭看這個問題點要如何解決。也許這過程中就像上述一下，一個腦袋突然靈光閃現，就解決了！～～</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb31a03cc8c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Get the value form HTML by Express]]></title>
            <link>https://medium.com/@wenliangsu65018/get-the-value-form-html-by-express-3b4844e2dba7?source=rss-9abbd74e1a5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b4844e2dba7</guid>
            <category><![CDATA[handlebars]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[Wen]]></dc:creator>
            <pubDate>Wed, 16 Nov 2022 16:47:30 GMT</pubDate>
            <atom:updated>2022-11-16T16:47:30.340Z</atom:updated>
            <content:encoded><![CDATA[<p>In Express, there are three that we can get value from the HTML. That are req.params, req.body, and req.query. However, the values that we got have a little different meaning.</p><p>1. req.params</p><p>the params is used to get the value from url. Here is a example as following:</p><p>edit.hbs</p><pre> &lt;form action=&quot;/restaurants/{{restaurantContent._id}}?_method=PUT&quot; method=&quot;POST&quot;&gt;<br>      &lt;div class=&quot;form-group mb-4 mt-6&quot;&gt;<br>        &lt;label for=&quot;name&quot; class=&quot;form-label&quot;&gt;中文店名 (Shop name in chinese)&lt;/label&gt;<br>        &lt;input<br>          type=&quot;text&quot;<br>          class=&quot;form-control&quot;<br>          id=&quot;name&quot;<br>          name=&quot;name&quot;<br>          maxlength=&quot;20&quot;<br>          placeholder=&quot;請輸入中文店名...&quot;<br>          value=&quot;{{restaurantContent.name}}&quot;<br>          required<br>        /&gt;<br>      &lt;/div&gt;<br>&lt;/form&gt;</pre><p>app.js (The router to get from edit.hbs)</p><pre>app.put(&quot;/:id&quot;, (req, res) =&gt; {<br>  const restaurantId = req.params.id;<br>  return Restaurant.findById(restaurantId)<br>    .then((restaurantEditedInfo) =&gt; {<br>      for (const [key, value] of Object.entries(req.body)) {<br>        restaurantEditedInfo[key] = value;<br>      }<br>      return restaurantEditedInfo.save();<br>    })<br>    .then(() =&gt; res.redirect(`/restaurants/${restaurantId}`))<br>    .catch((error) =&gt; {<br>      console.log(error);<br>      res.render(&quot;error&quot;, { error: error.message });<br>    });<br>});</pre><p>You can see it has form tag in edit.hbs and the action is a url which you want to show the specific data id. So the url will be http://locakhost:3000/restaurants/XXX_id?_method=PUT<em>. </em>When you use the req.params, it will show the id string in it object.(The id can be a number) And you can see the app.js get it by the req.params.id</p><p>2. req.body</p><p>In general, it used in POST and PUT method when you want to build the form in the web like the restaurant list or some sensitive data. The example is as following (app.js is the same as above)</p><p>edit.hbs</p><pre>      &lt;div class=&quot;form-group mt-4&quot;&gt;<br>        &lt;label for=&quot;phone&quot; class=&quot;form-label&quot;&gt;聯絡電話 (Shop phone number)&lt;/label&gt;<br>        &lt;input<br>          {{! !!注意電話的部分會不會變成number，資料格式是屬於字串 }}<br>          type=&quot;tel&quot;<br>          class=&quot;form-control&quot;<br>          id=&quot;phone&quot;<br>          name=&quot;phone&quot;<br>          placeholder=&quot;請輸入電話號碼 (please type your phone)&quot;<br>          value=&quot;{{restaurantContent.phone}}&quot;<br>          required<br>        /&gt;<br>      &lt;/div&gt;<br><br>      &lt;div class=&quot;form-group mt-4&quot;&gt;<br>        &lt;label for=&quot;category&quot; class=&quot;form-label&quot;&gt;料理類別(Food style)&lt;/label&gt;<br>        &lt;input<br>          list=&quot;category-options&quot;<br>          class=&quot;form-control&quot;<br>          id=&quot;category&quot;<br>          name=&quot;category&quot;<br>          placeholder=&quot;如無需要的選項，請自行填寫 (If you don&#39;t find out the option, please type yourself.)&quot;<br>          value=&quot;{{restaurantContent.category}}&quot;<br>          required<br>        /&gt;<br>        &lt;datalist id=&quot;category-options&quot;&gt;<br>          &lt;option&gt;義式料理 (Italy)&lt;/option&gt;<br>          &lt;option&gt;法式料理 (French)&lt;/option&gt;<br>          &lt;option&gt;日本料理 (Japan)&lt;/option&gt;<br>          &lt;option&gt;中東料理 (Middle East)&lt;/option&gt;<br>          &lt;option&gt;中式料理 (Chinese)&lt;/option&gt;<br>          &lt;option&gt;歐式料理 (European)&lt;/option&gt;<br>          &lt;option&gt;酒吧 (Bar)&lt;/option&gt;<br>          &lt;option&gt;咖啡廳 (Cafe)&lt;/option&gt;<br>        &lt;/datalist&gt;<br>      &lt;/div&gt;<br><br></pre><p>When the client side submit the form with content, it will be stored in the req.body and it is a JSON data. You have to pass the body-parse otherwise you will get an error</p><pre>app.use(express.urlencoded({ extended: true }));</pre><pre>app.use(express.urlencoded({ extended: true }));</pre><p>The input or button tag need to give their name to catch the value. Fro example, req.body in this example will be as following.</p><pre>req.body = {<br>   phone: XXX, // number<br>   category: &#39;XXXX&#39; // string<br>}</pre><p>3. req.query</p><p>It is usually used for searching, sorting, filtering , pagination, e.t.c. When client side send the keyword to searching something, the url will show the value and use the req.query to catch it.</p><p>index.hbs</p><pre> &lt;form action=&quot;/sort&quot; method=&quot;GET&quot;&gt;<br>    &lt;div class=&quot;input-group ms-2&quot; style=&quot;width: 200px; height:40px;&quot;&gt;<br>       &lt;select class=&quot;form-select text-center&quot; name=&quot;sort&quot; onchange=&quot;&quot;&gt;<br>          &lt;option value=&quot;a-z&quot; {{#if sort.a-z}}selected{{/if}}&gt;A-&gt;Z&lt;/option&gt;<br>          &lt;option value=&quot;z-a&quot; {{#if sort.z-a}}selected{{/if}}&gt;Z-&gt;A&lt;/option&gt;<br>          &lt;option value=&quot;category&quot; {{#if sort.category}}selected{{/if}}&gt;類別&lt;/option&gt;<br>          &lt;option value=&quot;location&quot; {{#if sort.location}}selected{{/if}}&gt;地址&lt;/option&gt;<br>        &lt;/select&gt;<br>        &lt;button type=&quot;submit&quot; class=&quot;btn btn-major&quot;&gt;排序&lt;/button&gt;<br>     &lt;/div&gt;<br>  &lt;/form&gt;</pre><p>app,js</p><pre>app.get(&quot;/sort&quot;, (req, res) = &gt; {    <br>    const reqValue = req.query<br>    const sortValue = reqValue.sort;<br>    const sortOption = {<br>      &quot;a-z&quot;: { name: &quot;asc&quot; },<br>      &quot;z-a&quot;: { name: &quot;desc&quot; },<br>      category: { category: &quot;asc&quot; },<br>      location: { location: &quot;asc&quot; },<br>    };<br><br>    const sort = sortValue ? { [sortValue]: true } : { &quot;a-z&quot;: true };<br><br>    Restaurant.find()<br>      .lean()<br>      .sort(sortOption[sortValue])<br>      .then((restaurantList) =&gt; res.render(&quot;index&quot;, { restaurantList, sort }))<br>      .catch((error) =&gt; {<br>        console.log(error);<br>        res.render(&quot;error&quot;, { error });<br>      });<br>})</pre><p>For example, the url will be <a href="http://localhost:3000/?sort=a-z">http://localhost:3000/?sort=a-z</a> (or z-a, location, category.)</p><p>Conclusion:</p><p>So, when we make the web with form and want to get these value, we have to know which method you have to use to catch it. req.query, req.body or req.params all of them have different meaning.</p><p>(if this article have the wrong place, please comment to me)</p><p>Ref:</p><p><a href="https://dev.to/gathoni/express-req-params-req-query-and-req-body-4lpc">https://dev.to/gathoni/express-req-params-req-query-and-req-body-4lpc</a></p><p><a href="https://medium.com/ling-ni-lee/express-js-%E5%8F%96%E5%BE%97%E7%B6%B2%E9%A0%81%E5%8F%83%E6%95%B8%E7%9A%84%E4%B8%89%E7%A8%AE%E6%96%B9%E6%B3%95-39725d8f3211">https://medium.com/ling-ni-lee/express-js-%E5%8F%96%E5%BE%97%E7%B6%B2%E9%A0%81%E5%8F%83%E6%95%B8%E7%9A%84%E4%B8%89%E7%A8%AE%E6%96%B9%E6%B3%95-39725d8f3211</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b4844e2dba7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>