--- tags: lecture --- # Express(backend) :::info ## Frontend review ### html => structure ```html= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Title</title> <link rel="stylesheet" href="main.css" /> </head> <body> <h1 id="hi">hi</h1> <script src="index.js"></script> </body> </html> ``` ### css => style ```css= h1 { color: red; } ``` ### javascript => interaction 寫在index.js(前端ㄉjs) ```javascript= document.getElementById("hi").onclick = () => alert("test"); ``` ::: ## Express Express 是最受歡迎的 Node web框架,他定義了各種 middlewares 來協助 client 跟 server 進行溝通 http://expressjs.com/ ## 安裝Express :::warning 先到 `class03_NodeJS/example-server` 底下 ::: ``` npm init -y ``` - npm 是 Node Package Manager,即「node包管理器」是Node.js預設的軟體套件管理系統。`init`會新增一個package.json檔,`-y`代表 yes,並會以 default 的方式去 initial,不會一一詢問。 ``` npm install express --save ``` - 在 npm 中,「Dependency」(依賴模組)是一個非常重要的概念,`--save` 的意思是將這個 package 設定為本次專案的 dependency(告訴這個專案說:這次的專案需要依賴於這個模組才能運作)。 ## 設定伺服器(Server) ### `server.js`(後端ㄉ js) ```javascript= const express = require('express') const app = express() // 建立一個 Express 伺服器 const port = 3000 app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`) // 告訴 server 聽取特定 port }); ``` 在 terminal 輸入 `node server.js` 看看會發生什麼? ### Routing Routing 是把網址 (URL) 轉給特定程序處理的過程,告訴伺服器接收 Request 和回傳 Response 的方法 - 常見的 request method (前四種): ![](https://i.imgur.com/AvYCXEh.png) 我們會針對不同 Request 設計做不同事情,回傳不同 Response ```javascript= /* Routes Definitions */ app.get('/', (req, res) => { res.sendFile(path.join(__dirname, '/static/index.html')); }) app.get("/test", (req, res) => { res.send("<h1>Test</h1>") }) ``` ### Sending Parameters: `req.params` ```javascript= const users = [ { id: 1, name: "Joe", age: 18, }, { id: 2, name: "John", age: 22, }, ]; app.get("/users/:id", function (req, res) { const user = users.filter((u) => u.id == req.params.id); if (user.length() > 0) { res.send(`<h1>Hi! ${user[0].name}</h1>`); } else { res.send(`<h1>User Not Found</h1>`); } }); ``` ## Let's Play: Simple Login Server ### Structure ``` └── simple-login-server ├── package.json ├── server.js └── static ├── index.html └── login.html ``` #### 1. `npm init -y` #### 2. `npm install express` #### 3. Set up routes for our GET requests ```javascript= // Route to Homepage app.get('/', (req, res) => { res.sendFile(path.join(__dirname + '/static/index.html')); }); // Route to Login Page app.get('/login', (req, res) => { res.sendFile(path.join(__dirname + '/static/login.html')); }); ``` ```javascript= app.post('/login', (req, res) => { // Insert Login Code Here let username = req.body.username; let password = req.body.password; res.send(`Username: ${username} Password: ${password}`); }); ``` #### 5. Start the server `node server.js` ## Challenage: Check password - [ ] 存幾組帳號密碼(用變數存?用另一個file存?) - [ ] 用正確帳號密碼登入進入成功頁面(帳號存不存在?密碼是否正確?) - [ ] 帳號密碼錯誤進入登入失敗頁面