# Node + Express 首先,需安裝express ```javascript= $ npm install express --save ``` 開啟一個js檔,並載入express ```javascript= let express = require('express') let app = express() let port = 8000 app.get('/', (req, res) => { res.send('hello express') }) app.listen(port) ``` ### 製作表單送出 ```javascript= app.get('/', (req, res) => { res.send(` <form action="/answer" method="post"> <h1>天空的顏色</h1> <input name="sky"> <button>送出</button> </form> `) }) ``` #### 新增路徑POST ```javascript= app.post('/answer', (req,res) => { res.send('感謝填寫') }) ``` #### 如何取得input內容 ```javascript= req.body.[input name] ``` #### 加入判斷 ```javascript= app.post('/answer', (req,res) => { if(req.body.sky === '藍色') { res.send('bingo') } else { res.send('WRONG') } res.send('感謝填寫') }) ``` ## Middleware中介軟體 介於發出請求至接收回應,負責執行某些處理,可以決定是否繼續執行或中斷。 在上方的程式碼中需加入這段middleware ```javascript= app.use(express.urlencoded({ extended: false })) ``` 在POST、PUT的請求才需加入上面這段去決定要怎麼解析req.body的內容
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up