一.Express簡介
Express提供了一個輕量級模塊,把Node.js的http模塊功能封裝在一個簡單易用的接口中。Express也擴(kuò)展了http模塊的功能,使你輕松處理服務(wù)器的路由、響應(yīng)、cookie和HTTP請求的狀態(tài)。使用Express可以充當(dāng)Web服務(wù)器。
二.搭建基于express框架運(yùn)行環(huán)境 開發(fā)后端的node服務(wù)
1.安裝express
① 安裝全局變量 npm install express-generator -g (全局變量會在C盤node文件下)
②查看安裝成功:express -version
2.通過生成器自動創(chuàng)建項(xiàng)目
找到項(xiàng)目安裝地址: 執(zhí)行 express server就出現(xiàn)下面文件

在這個目錄下安裝express: npm install express --save 因?yàn)槿职惭bexpress沒可能沒安裝全
3.運(yùn)行項(xiàng)目
注意:因?yàn)槲疫@邊是為了方便演示練手,所以我沒有進(jìn)行前后端分析,所以我 express搭建的package.json 與vue搭建package.json進(jìn)行合并
(1).合并package.json

(2).在項(xiàng)目vue-nodesel下安裝依賴包
執(zhí)行命令:cnpm install
(3).進(jìn)入express安裝的項(xiàng)目server
cd server
(4).運(yùn)行項(xiàng)目:node bin/www 
在瀏覽器中輸入 http://localhost:3000或是http://127.0.0.1:3000/

如圖所示,我們已經(jīng)訪問成功了。
三.express + Ejs實(shí)現(xiàn)一個簡單的WebServer
1.在項(xiàng)目vue-nodesel,安裝ejs
cnpm install ejs --save
2.在express安裝的項(xiàng)目server中app.js引入
var ejs = require('ejs')app.engine('.html',ejs._express);app.set('view engine', 'html');
3.在express安裝的項(xiàng)目server中 views創(chuàng)建index.html
<!DOCTYPE html><html><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><title>Examples</title><meta name="description" content=""><meta name="keywords" content=""><link href="" rel=" rel="external nofollow" stylesheet"></head><body> hello,EXpress is very Goods!</body></html>
4.運(yùn)行項(xiàng)目:node bin/www 

四.express開啟web服務(wù)整體流程
--》1.server.js 利用express開啟web服務(wù)器		//1.導(dǎo)入express,mongoose模塊			const express= require('express')		//2利用express對象創(chuàng)建一個application對象 			const app = express()						//4.路由  路由的引用操作 如:			//4.1路由的引用			const userRouter = require('./user')			//4.2使用use 開啟中間件			app.use('/user',userRouter);  			//開發(fā)注意事項(xiàng):路由引用到在app.listen之前 					//3.監(jiān)聽端口并訪問 利用app.listen()監(jiān)聽端口			app.listen(9093,() =>{				console.log("服務(wù)器已經(jīng)運(yùn)行,請打開瀏覽器,輸入:http://localhost:9093/ 來")			}) --》2.路由規(guī)則放入到一個js文件中,寫好相應(yīng)的代碼,并且暴露出去		如:路由user.js		//1.引入express模塊 使用router對象 			const express = require('express');		//2.創(chuàng)建一個路由		const route = express.Router(); 				//4.在這里面做數(shù)據(jù)的增刪改操作  路由的處理...				//3.將創(chuàng)建的路由對象暴露出去		module.exports = route;  --》3.在server.js中,導(dǎo)入對應(yīng)的路由(user.js),并且調(diào)用app.use方法使用即可		就是1中的第4步驟			const route = require('路由的路徑');			app.use('路由規(guī)則',route); //哪些路由規(guī)則適用于該路由以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答