--- tags: 110-1 --- # 11/26 部課 ## TODO - [ ] js review: callback function - [ ] arrow function - [ ] web review - [ ] express review - [ ] more express - [ ] python flask - [x] 選部遊長 - [ ] 啥時部遊 ## Javascript ### Recall: Callback function 在一個 function 中藉由 argument 去呼叫另一個 function () ```javascript= function greeting(name) { alert('Hello ' + name); } function processUserInput(callback) { var name = prompt('輸入你的名字:'); //會跳出小視窗讓你輸入 callback(name); } processUserInput(greeting); ``` ### Arrow function 一種非常簡短的 function 語法 - 一般 function寫法 ```javascript= function greeting(name) { alert('Hello ' + name); } function sum(a, b) { return a+b } ``` - arrow function 1: (參數1, 參數2, …, 參數N) => { statements; } ```javascript= (name) => { alert('Hello' + name); } // 如果只有一個 argument 可以不加括號 name => { alert('Hello' + name); } // 若無參數,就一定要加括號 () => { statements } ``` - arrow function 2: (參數1, 參數2, …, 參數N) => expression; ```javascript= (a, b) => a+b; (a, b) => (a+b) //等相同(參數1, 參數2, …, 參數N) => { return expression; } (a, b) => {return a+b;} ``` 就是因為他非常簡短,所以我們常常會跟 callback function 搭配使用: ```javascript= function processUserInput(callback) { var name = prompt('輸入你的名字:'); //會跳出小視窗讓你輸入 callback(name); } processUserInput((name) => {alert('Hello' + name);}); ``` 這樣就可以不用分兩部份寫了! ## World Wide Web 溝通:HTTP ### 流程 ![](https://i.imgur.com/5bBU4Br.png) ### Request 跟 response 長什麼樣子? 可以從 Insecpt > Network 去看 #### Request ![](https://i.imgur.com/XP408wy.png) * GET 方法請求展示指定資源。使用 GET 的請求只應用於取得資料。 * POST 方法用於提交指定資源的實體,通常會改變伺服器的狀態或副作用。 * PUT 方法會取代指定資源所酬載請求(request payload)的所有表現。 * DELETE 方法會刪除指定資源。 #### Response ![](https://i.imgur.com/W8zXGRe.png) * Status code: https://http.cat/ * 1xxs – Informational responses * 2xxs – Success! * 3xxs –Redirection * 4xxs – Client errors * 5xxs – Server errors ## Express Review ``` npm init -y npm install express --save ``` ```javascript= const express = require('express') const app = express() // 建立一個 Express 伺服器 const port = 3000 app.get('/', (req, res) => { res.send("<h1>Hello World</h1>"); }); app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`) // 告訴 server 聽取特定 port }); ``` ``` node server.js ``` ## More about Express ### nodemon 在開發的時候,會要一直修改code,如果每次修改都要重新跑過一次 `node server.js`,就會很花時間也麻煩,這時我跟就可以使用 nodemon 幫我們自動重啟! ``` npm install -D nodemon ``` 我們會希望開發階段(development)時用 nodemon 啟動我們的 server,正式階段(production) 時用 node 啟動 ```json= "scripts": { "start": "node server.js", "dev": "nodemon server.js" }, ``` ```bash= npm start # 跑 node server npm run dev # 跑 nodemon server ``` ### 環境變數 - 使用時機? 環境變數的功能就是把散佈在各個檔案且會在不同環境需要調整的參數集合到一個檔案裡面 - 常用情境如下: 1. 用來區分正式(prod) / 測試(dev)環境 1. 設定重要不得外流的資料(資料庫帳號、密碼,使用者權杖...) 1. 需要統一設定的變數內容(系統ip、網址、port...) #### DotEnv DotEnv is a lightweight npm package that automatically loads environment variables from a .env file into the process.env object. ``` npm i dotenv ``` 創一個 .env 檔,把一些內容放進去: ``` HOST = localhost PORT = 3000 ``` 把以下加入在 server.js ```javascript= require('dotenv').config() const port = process.env.PORT || 3000; ``` ### Static Folder 如果要提供影像、html、CSS、JavaScript等之類的靜態檔案,可以一起放在一個 folder (e.g. public/) 去 serve ```javascript= app.use(express.static('public')); ``` ### 將 routing 獨立出來 - `express.Router()`: Creates a new router object. - `app.route(path)`: Returns an instance of a single route, which you can then use to handle HTTP verbs with optional middleware. Use app.route() to avoid duplicate route names (and thus typo errors). ```javascript= // api.js const app = express() const router = express.Router() router.route('/users/:user_id') .all(function (req, res, next) { }) .get(function (req, res, next) { }) .put(function (req, res, next) { }) .post(function (req, res, next) { }) .delete(function (req, res, next) { }) ``` https://expressjs.com/en/4x/api.html ## Flask Python Flask 是一種輕量級的網頁框架,只要五行程式碼,就可以架設網頁伺服器 : ### 步驟一 : 安裝 Flask 套件 ``` $ pip install Flask ``` ### 步驟二 : 將以下代碼存檔為 app.py ```python= from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello, World!" ``` ### 步驟三 : 終端機指令執行 ``` $ flask run ``` 出現「Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)」的文字