express怎麼用?
如何獲取請求?
如何處理響應?
如何對向外暴露靜態資源?
express核心:中間件:如何理解?javascript
中間件:用來處理 http 請求的一個具體的環節(可能要執行某個具體的處理函數)
中間件通常都是經過修改 req 或者 res 對象來爲後續的處理提供便利的使用
中間件分類:
use(function () {req, res, next})
不關心請求方法和請求路徑,沒有具體路由規則,任何請求都會進入該中間件
use('請求路徑', function (req, res, next) {})
不關心請求方法,只關心請求路勁的中間件
get('請求路徑', function (req, res, next) {})
具體路由規則中間件
post('請求路徑', function (req, res, next) {})
css
// 需求一:用戶訪問 / 響應 hello world // 需求二:用戶訪問 /login 響應 hello login // 需求三:將 public 目錄開放爲相似於 Apache 同樣,能夠直接經過路徑去取訪問該目錄中的任意資源 const express = require('express') const fs = require('fs') // 1. 調用 express() 方法,獲得一個 app 實例接口對象(相似於 http.createServer 獲得的 server 實例) const app = express() // 這個就表示是一箇中間件 // 目前下面這個 API ,任何請求進來都會執行對應的處理函數 // 不關心當前請求的具體請求方法和請求路徑 // 該代碼內部若是不發送響應或者作進一步處理則代碼會一直停在這裏,不會日後執行 app.use(function (req, res, next) { const urlPath = req.path // /puiblic/a.css // /public/main.js if (urlPath.startsWith('/public/')) { const filePath = `.${urlPath}` // 這裏加 . 的緣由是由於若是讀文件是以 / 開頭的則會去當前文件所屬磁盤根目錄去查找 fs.readFile(filePath, (err, data) => { if (err) { return res.end('404 Not Found.') } res.end(data) }) } else { // 若是請求路徑不是以 /public/ 開頭的,則調用 next ,next 是一個函數(不肯定) // 這裏調用了 next 的目的就是告訴 Express 繼續日後執行:中間件 // 具體執行哪一個中間件:取決於對應的中間件的類型 next() } }) // 2. 經過 app 設置對應的路徑對應的請求處理函數 // 回調處理函數中: // req 請求對象:用來獲取當前客戶端的一些請求數據或者請求報文信息 // 例如 req.query 用來獲取查詢字符串數據 // req.method 用來當前請求方法 // res 響應對象:用來向當前請求客戶端發送消息數據的 // 例如 res.write('響應數據') // res.end() 結束響應 app.get('/', (req, res) => { res.write('hello ') res.write('expres') res.end() }) app.get('/login', (req, res) => { // end 用來結束響應的同時發送響應數據 res.end('hello login') }) // 3. 開啓監聽,啓動服務器 app.listen(3000, () => { console.log('服務已啓動,請訪問:http://127.0.0.1:3000/') })
對於相同請求重複兩次,會怎樣處理?------對於一次請求來講,只能響應一次java
express中的中間件
app.use('/public', express.static('開放目錄的路徑'))
node
在 use 方法中,若是指定了第一個路徑參數,則經過req.path
獲取到的是不包含該請求路徑的字符串
例如當前請求路勁是/public/a.jpg
則經過req.path
拿到的就是 a.jpg
/public/a/a.css a/a.css
目前已知傳遞給了 static 方法一個絕對路徑c:/project/public
假設目前請求是 /public/a/a.css
拿到的 req.path a/a.css
c:/project/public + a/a.cs
拼接起來,讀取express
const express = require('express') const fs = require('fs') const path = require('path') const static = require('./middlwares/static') const app = express() app.use('/public', static(path.join(__dirname, 'public'))) app.use('/node_modules', static(path.join(__dirname, 'node_modules'))) app.get('/', (req, res, next) => { console.log('/ 111') res.end('hello') next() }) app.get('/', (req, res, next) => { console.log('/ 222') // 1. 在 http 中,沒有請求就沒有響應,服務端不可能主動給客戶端發請求,就是一問一答的形式 // 2. 對於一次請求來講,只能響應一次,若是發送了屢次響應,則只有第一次生效 res.end('world') next() }) app.use((req, res, next) => { console.log(111) // 假若有請求進入了該中間件,這裏調用的 next 會執行下一個能匹配的中間件 // get / // get /a next() }) // / 111 222 333 // /a 111 use /a // /a next() 111 use/a 222 333 app.use('/a', (req, res, next) => { console.log('use /a') next() }) app.use((req, res, next) => { console.log(222) next() }) app.use((req, res, next) => { console.log(333) }) app.listen(3000, () => { console.log('服務已啓動,請訪問:http://127.0.0.1:3000/') })
const fs = require('fs') const path = require('path') module.exports = function (dirPath) { // 這裏不須要調用 next // 由於若是不是以 /public 開頭的,當前這個中間件壓根兒就不會進來 return (req, res, next) => { const filePath = path.join(dirPath, req.path) fs.readFile(filePath, (err, data) => { if (err) { return res.end('404 Not Found.') } res.end(data) }) } }
該處理放在前面,要保證其每次發起請求都被執行到,並記錄日誌json
const express = require('express') const fs = require('fs') const path = require('path') const static = require('./middlwares/static') const app = express() app.use((req, res, next) => { const log = `請求方法:${req.method} 請求路徑:${req.url} 請求時間:${+new Date()}\n` fs.appendFile('./log.txt', log, err => { if (err) { return console.log('記錄日誌失敗了') } next() }) }) app.listen(3000, () => { console.log('服務已啓動,請訪問:http://127.0.0.1:3000/') })
請求方法:GET 請求路徑:/ 請求時間:1486537214226請求方法:GET 請求路徑:/favicon.ico 請求時間:1486537214735請求方法:GET 請求路徑:/ 請求時間:1486537249534 請求方法:GET 請求路徑:/favicon.ico 請求時間:1486537250459 請求方法:GET 請求路徑:/ 請求時間:1486537253228 請求方法:GET 請求路徑:/favicon.ico 請求時間:1486537254353
注意這裏這兩種中間的所處位置api
const express = require('express') const fs = require('fs') const app = express() app.get('/', function aaa(req, res, next) { // 經過 JSON.parse 解析查詢字符串中的某個 try { const data = JSON.parse('{abc') res.json(data) } catch (e) { next(e) } }) app.get('/a', (req, res, next) => { fs.readFile('./dnsajndsja', (err, data) => { if (err) { // 這裏調用的 next 會被 app.use((err, req, res, next)) 這個中間件匹配到 next(err) } }) }) app.get('/b', (req, res, next) => { res.end('hello index') }) // 該中間件只有被帶有參數的 next 才能調用到 // 帶參數的 next 只能被具備四個參數的處理中間件匹配到 // 注意:這裏必定要寫全四個參數,不然會致使問題 // 這個中間件就是用來全局統一處理錯誤的 app.use((err, req, res, next) => { const error_log = ` ==================================== 錯誤名:${err.name} 錯誤消息:${err.message} 錯誤堆棧:${err.stack} 錯誤時間:${new Date()} ====================================\n\n\n` fs.appendFile('./err_log.txt', error_log, err => { res.writeHead(500, {}) res.end('500 服務器正忙,請稍後重試') }) }) // 404 處理中間件 app.use((req, res, next) => { res.end('404') }) app.listen(3000, () => { console.log('running...') })
==================================== 錯誤名:SyntaxError 錯誤消息:Unexpected token a in JSON at position 1 錯誤堆棧:SyntaxError: Unexpected token a in JSON at position 1 at Object.parse (native) at aaa (C:\Users\lpz\Desktop\00-Node-第2天-內容一、內容2\4-源代碼\express-demo\app-middleware-404.js:9:23) at Layer.handle [as handle_request] (C:\Users\lpz\Desktop\00-Node-第2天-內容一、內容2\4-源代碼\express-demo\node_modules\express\lib\router\layer.js:95:5) at next (C:\Users\lpz\Desktop\00-Node-第2天-內容一、內容2\4-源代碼\express-demo\node_modules\express\lib\router\route.js:131:13) at Route.dispatch (C:\Users\lpz\Desktop\00-Node-第2天-內容一、內容2\4-源代碼\express-demo\node_modules\express\lib\router\route.js:112:3) at Layer.handle [as handle_request] (C:\Users\lpz\Desktop\00-Node-第2天-內容一、內容2\4-源代碼\express-demo\node_modules\express\lib\router\layer.js:95:5) at C:\Users\lpz\Desktop\00-Node-第2天-內容一、內容2\4-源代碼\express-demo\node_modules\express\lib\router\index.js:277:22 at Function.process_params (C:\Users\lpz\Desktop\00-Node-第2天-內容一、內容2\4-源代碼\express-demo\node_modules\express\lib\router\index.js:330:12) at next (C:\Users\lpz\Desktop\00-Node-第2天-內容一、內容2\4-源代碼\express-demo\node_modules\express\lib\router\index.js:271:10) at expressInit (C:\Users\lpz\Desktop\00-Node-第2天-內容一、內容2\4-源代碼\express-demo\node_modules\express\lib\middleware\init.js:33:5) 錯誤時間:Wed Feb 08 2017 15:52:52 GMT+0800 (中國標準時間) ==================================== ==================================== 錯誤名:Error 錯誤消息:ENOENT: no such file or directory, open 'C:\Users\lpz\Desktop\00-Node-第2天-內容一、內容2\4-源代碼\express-demo\dnsajndsja' 錯誤堆棧:Error: ENOENT: no such file or directory, open 'C:\Users\lpz\Desktop\00-Node-第2天-內容一、內容2\4-源代碼\express-demo\dnsajndsja' at Error (native) 錯誤時間:Wed Feb 08 2017 15:53:14 GMT+0800 (中國標準時間) ====================================
express官網服務器