Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js' package ecosystem, npm, is the largest ecosystem of open source libraries in the world.
windowsjavascript
LTS
版本,下載安裝包,Current
版本是開發版,不要下載,如圖ubuntucss
運行如下命令html
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash - sudo apt-get install -y nodejs
mac前端
安裝完成後,運行以下命令檢查是否安裝成功,(以上方法安裝node都會帶上對應的npm,因此也須要檢查一下npm是否安裝成功。)java
node -v // 檢查node版本 npm -v // 檢查npm版本
Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.
npm install express -g // 全局安裝express npm install express-generator -g // 全局安裝express腳手架,安裝以後可使用express命令 express --version // 檢查express版本
mkdir app cd app /** * 生成項目文件 * express 默認使用ajs模板,加上 -e 指定更友好的ejs模板 */ express -e npm intall // 安裝依賴 npm start // 啓動項目
而後瀏覽器訪問localhost:3000
,最簡單的服務器就ok了。node
如何修改程序啓動的默認3000
端口
Express 的啓動目錄是<project>/bin/www
,裏面有一行代碼:web
var port = normalizePort(process.env.PORT || '3000');
不難看出程序先去取process.env.PORT
(環境變量PORT)的值,沒有就默認爲3000
因此若是想改變端口,能夠直接把3000
改爲想要的端口號或者修改環境變量PORT的值,操做以下:
在啓動程序以前,執行express
// ubuntu IOS export PORT=4000; // windows set PORT=4000;
而後執行npm start
,端口就被設置成了4000.npm
如何修改運行環境
Express默認的運行環境是development
,運行環境能夠經過process.env.NODE_ENV
來獲取,將系統環境設置爲production
,代碼以下:json
// ubuntu IOS export NODE_ENV=production // wondows set NODE_ENV=production
如何添加接口
在app.js
中,app.use('/', routes);
前面新增
app.get('/status', function (req, res) { res.send({status: 'ok'}); })
啓動服務器,訪問localhost:3000/status
,獲得數據{status: 'ok'}
;
具體分析一下:app.get()
, get
是app對象的一個方法,負責處理get方法,改爲post
,則只處理post
請求,不會處理別的請求,其他像put
,delete
相似。若寫成use
,則會處理此路由任何方法的請求。/status
, 指定須要處理的路由
回調函數,即請求此路由的處理函數,它能夠接收兩個參數,三個參數,四個參數。一旦參數爲四個就被express認定是錯誤處理函數
// app.js 裏這就是個錯誤處理函數,用來處理全部路由上面拋出的錯誤,通常寫在最後 app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); });
req
Express 封裝的http request對象,包含headers
,query
,params
等自帶屬性。用來獲取某次http請求的各項數據。
res
Express 封裝的http reponse對象,包含send
,json
,jsonp
等方法。
next
若是執行next
,在執行完此處理函數以後,會繼續向後找下一個處理函數,
app.get('/test-next', function(req, res, next) { console.log('first handler fn'); next(); }); app.get('/test-next', function(req, res, next) { res.send({status: 'second handler fn'}); });
瀏覽器訪問localhoat:3000/test-next
,會獲得{status: 'second handler fn'}
,
處理路由/test-next
,第一個回調函數,執行到next()
時,繼續找下一個能處理/test-next
的回調.
什麼是中間件
中間件(middlewear)是Express中的一個重要概念,Express使用中間件完成對請求體的改造,或者執行一些中間操做。歸根結底,中間件就是一個函數,知足兩個條件,
req
,res
,next
三個參數,最後執行next
函數,將處理權移交出去
寫一個打印請求的中間件:
// 定義中間件,打印請求的方法和url function logRequest(req, res, next) { console.log(req.method, method.url); next(); } // 使用中間件 app.use(logRequest);
Express 如何處理路由
對於一個請求,Express處理通過一下流程
next()
則再也不往下執行,若是執行了next()
,會繼續向下匹配。404
處理中間件,這個中間件會拋出一個錯誤,交由錯誤處理中間件處理。理解靜態資源處理中間件app.use(express.static(path.join(__dirname, 'public')));
,express.static(PATH)
會將指定的目錄下的全部資源做爲靜態資源。客戶端能夠輸入指定資源的路徑訪問此資源。其實能夠理解爲將靜態資源的路徑,做爲路由註冊到了app
上。
若是要將文件<project>/public/stylesheets/style.css
,設置爲靜態資源,能夠指定靜態文件目錄
app.use(express.static(path.join(__dirname, 'public')));
也能夠不設置靜態文件,自定義路由
app.get('/stylesheets/style.css', function (req, res, next) { res.sendFile(path.join(__dirname, 'public/stylesheets/style.css')); })
兩種方式訪問http://localhost:3000/stylesheets/style.css
都能獲得style.css
文件。
靜態資源和用戶自定義路由是等價的,因此,通常將靜態資源處理中間件放在用戶自定義中間件前面,避免路由衝突。
如何使用模板(默認使用ejs模板引擎)
// path 爲.ejs模板的路徑 // data 是給模板傳入的值,必須是對象類型 res.render(<path>, [data]);
例如
app.js
app.get('/ejs', function(req, res, next) { res.render('index', { title: 'Express' }); });
index.ejs
<h1><%= title %></h1> <p>test ejs</p>
訪問localhost:3000/ejs
便可看到結果。
ejs的經常使用語法以下
<% %> 在標籤裏能夠寫任意的 javascript 代碼,能夠把 javascript 代碼拆開或者合在一塊兒寫,也能夠與 html 標籤一塊兒寫:
<% var a = 1 var b = 2 var c = a+b %> // var user = [1,2,3] <% for(let i=0; i<user.length; i++) { %> <p> html </p> <% } %>
<%= %> 輸出轉義後的內容
// ejs <p><%= '<lol>' %></p> // 轉義後 <p><lol></p>
<%- %> 輸出未轉義的內容
// ejs <p><%- '<a href="http://www.baidu.com>baidu</a>' %></p> // 不轉義的輸出 <p><a href="http://www.baidu.com>baidu</a></p>
include 引入其餘 ejs 文件,好比引用當前 ejs 文件同級目錄下有一個名爲 test.ejs 的文件,代碼以下:
// exp1 <% var data = 1 %> <% include ./test %> // exp2 <%- include('test', {data:1}) %>