# [GDSC] NodeJS (3) [TOC] > 我不是 Javascript 專業,講錯歡迎指教 --- ## Express Prerequisite > [!Note] Reference > - [Express Docs](https://expressjs.com/) ### Installation - 官方提供框架套件安裝指令 : ```bash= npm install --save express ``` - [Express Generator](https://www.npmjs.com/package/express-generator) : ```bash= npm install -g express-generator ``` ```bash= # Initialize express --view=[TEMPLATE_ENGINE] [Folder] # Install dependencies npm install # Start running at http://localhost:3000 (default) npm start ``` ### Project Structure ``` - bin/www 載入主程式以及 server, address, port 設定 - public/ 主要是一些 style sheets 以及 images 的 static resources - routes/ 路由目錄 - views/ 放置 view file (according to template engine) - app.js 設置 view engine, middlewares, routes - package.json 主要是跑程式的 scripts 以及 npm install 的套件 ``` --- ## MVC Pattern 對應先前所述 : - Model 可以對應到 mongoose 的 Schema - View template engine (e.g., pug) 呈現的內容 - Controller 大概就是那些 HTTP request method 處理的東西 <img src='https://miro.medium.com/v2/resize:fit:1100/format:webp/1*ShfLwhnTPQ6SIGckSGpAQw.png'> ### Online Resources [MDN Tutorial - Express web framework (Node.js/JavaScript)](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs) --- ## API Protocol <img src='https://media.licdn.com/dms/image/D4D12AQGf2tfmrTOkYA/article-inline_image-shrink_1500_2232/0/1707811800485?e=1727308800&v=beta&t=Gb7zHukHZsbX-zQS7fUplceDTl-M1vi0_O8TbnVMB5I'> ### REST (Representational State Transfer) >[!Tip] Features > - 使用標準的 HTTP 協定 > GET, POST, DELETE, PUT... > - 基於 JSON > - Stateless 不由 Server-side 儲存狀態,由 Client-side 管理狀態,可使用 `localStorage`, `sessionStorage`, 或是 React 中的 `useState` >[!Warning] Disadvantages > - CRUD 不夠靈活 :question: What is **so-called REST** ### GraphQL >[!Tip] Features > - 支援 [Query language](https://graphql.org/) > - 靈活性高 > 可以根據需求索取需要的資料 (減少過多資料傳輸) >[!Warning] Disadvantages > - 學習曲線較高 > - 大型查詢會有性能隱憂 ### gRPC (gRPC Remote Procedure Calls) >[!Tip] Features > - 使用 [ProtoBuf(Protocol Buffers)](https://protobuf.dev/)作為定義語言 > 副檔名以 `.proto` 結尾 > - HTTP/2 > 傳送 binary, TCP 多路覆用等特性 > - 適用於微服務 (microservices) 架構 >[!Note] More details > GeeksforGeeks - [Difference between HTTP/2 and HTTP/1.1 ](https://www.geeksforgeeks.org/difference-between-http-2-and-http-1-1/) >[!Warning] Disadvantages > - 流量控制與錯誤處理相對複雜 ### WebSockets >[!Tip] Features > - Real-time > - 全雙工,透過單一 TCP 連接實現 > - Continuous connection > - 適用於在線遊戲, 即時聊天服務 >[!Warning] Disadvantages > - 不支援 Stateless (資源消耗) > - 網路代理與防火牆設定 ### SOAP (Simple Object Access Protocol) >[!Tip] Features > - 基於 XML > - 企業級應用,具有嚴格的 Transaction 以及 Security 規範 > - 主要使用 HTTP 作為傳輸協定 (HTTPS 需要使用 WS-Security) >[!Warning] Disadvantages > - 同時也相對的耗費資源 > - 伺服器需要儲存先前與客戶端交換的所有資訊來維護狀態 ### Webhook >[!Tip] Features > - Event-driven, Asynchronous, HTTP Callback > - 用於觸發自動化流程,像是 Workflow automation (CI/CD), Third-party services integrations (Github, Jenkins) >[!Warning] Disadvantages > - 安全性管理,包含偽造請求、數據洩漏