[Express] 安裝Express
- 創建資料夾
mkdir express_basic
- 進入資料夾
cd express_basic
- 初始化
pakcage.json
執行指令npm init -y
- 透過 npm 指令安裝 express:
npm install express
- 透過 npm 指令安裝 nodemon:
npm install -g nodemon
- 簡單範例
-
// Include express from node_modules const express = require('express') const app = express() // 在Express中,如果沒有定義 hostname,Express 就是預設用 loclhost const port = 3000 // app.get - 設定路由 // app.send - 設定伺服器回應的內容 // app.listen - 啟動伺服器去監聽 app.get('/', (req, res) => { res.send(`This is my first Express Web App started by nodemon !!!!!!!`) }) app.get('/food', (req, res) => { res.send('My favorite food is ice cream') }) app.get('/popular/languages', (req, res) => { res.send('JavaScript is a popular language') }) app.get('/popular/languages/:language', (req, res) => { console.log('request params language is: ', req.params.language) res.send(`<h1>${req.params.language}is a popular language<h1>`) }) // Start and listen the server app.listen(port, () => { console.log(`Express is running on http://localhost:${port}`) })
- 透過
nodemon
執行app.js
就可以啟動伺服器 - end
-