Express 新手教學,起步走
Nodejs Express 框架
Nodejs Express 屬於輕量型框架,本篇文章寫架設 Express 起步走的新手教學
Express
安裝起步走1
2
3$ mkdir express-practice && cd express-practice
$ npm init
$ npm install express --save
設定 Web Server
建立 app.js
1 |
|
執行 app.js 啟動 Web 伺服器
1 |
|
網址規則
https://wualnz.com/search?q=express
- http:傳輸協定,通常是 https,才會出現綠色安全鎖頭
- wualnz: 主網域,由域名供應商提供
- 子網域:www.wualnz.com, email.wualnz.com
- ?q=express:Query 參數,解析出來會是
{q: 'express'}
HTTP 協定
GET1
app.get('/', (req,res) => res.send('GET Response'))
POST1
app.post('/', (req,res) => res.send('GET Response'))
可以將 get, post 替代成以下 HTTP 方法
get、post、put、head、delete、options、 trace、copy、lock、mkcol、move、purge、propfind、proppatch、unlock、report、mkactivity、checkout、merge、m-search、notify、subscribe、unsubscribe、patch、search,以及 connect
Query 參數
開頭會有 ?,每個參數都會有 & 的符號做連接example.com/search?q=hello
text=hello
text=hello&today=coolman
1 |
|
靜態路由
靜態路由,網址輸入 /user/profile 會到「瀏覽個人檔案」、 /user/edit-profile,會到「編輯個人檔案」1
2
3
4
5
6app.get('/user/profile', (req, res) => {
res.send('瀏覽個人檔案')
})
app.get('/user/edit-profile', (req, res) => {
res.send('編輯個人檔案')
})
動態路由
wualnz.com/user/hazel
,取得 hazel 動態的名字,不同使用者會輸入不同的名字,可以藉由 req.params 取得指定路徑
路由設定 :name
,再用 req.params.name
去接到參數
1 |
|
query 取得網址參數
wualnz.com/search?q=express
抓取網址列上的參數 q=express
資料
1 |
|
Router 進階
新增 routes 資料夾,並在 routes資料夾建立 user.js
目錄結構
- routes
- user.js
user.js1
2
3
4
5
6
7
8const express = require('express')
const router = express.Router()
router.get('/user/profile', (req, res) => {
res.send('Profile)
})
module.exports = router
app.js 讀取 user router1
2
3
4
5const express = require('express')
const app = express()
const user = require('./router/user')
app.use('/user', user)
此方法可以大幅降低 app.js 肥沃的程度,也會變得相當乾淨、簡潔
常用工具
express-generator
快速建立應用程式的架構1
$ npm install express-generator
-e –ejs: 產生 ejs template
-e –hbs: 產生 handlebars template
-e –pug: 產生 pug tempalte
1 |
|
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!