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

在這個目錄下安裝express: npm install express --save 因為全局安裝express沒可能沒安裝全
3.運行項目
注意:因為我這邊是為了方便演示練手,所以我沒有進行前后端分析,所以我 express搭建的package.json 與vue搭建package.json進行合并
(1).合并package.json

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

如圖所示,我們已經訪問成功了。
三.express + Ejs實現一個簡單的WebServer
1.在項目vue-nodesel,安裝ejs
cnpm install ejs --save
2.在express安裝的項目server中app.js引入
var ejs = require('ejs')
app.engine('.html',ejs._express);
app.set('view engine', 'html');

3.在express安裝的項目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.運行項目:node bin/www

四.express開啟web服務整體流程
--》1.server.js 利用express開啟web服務器
//1.導入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ā)注意事項:路由引用到在app.listen之前
//3.監(jiān)聽端口并訪問 利用app.listen()監(jiān)聽端口
app.listen(9093,() =>{
console.log("服務器已經運行,請打開瀏覽器,輸入:http://localhost:9093/ 來")
})
--》2.路由規(guī)則放入到一個js文件中,寫好相應的代碼,并且暴露出去
如:路由user.js
//1.引入express模塊 使用router對象
const express = require('express');
//2.創(chuàng)建一個路由
const route = express.Router();
//4.在這里面做數據的增刪改操作 路由的處理...
//3.將創(chuàng)建的路由對象暴露出去
module.exports = route;
--》3.在server.js中,導入對應的路由(user.js),并且調用app.use方法使用即可
就是1中的第4步驟
const route = require('路由的路徑');
app.use('路由規(guī)則',route); //哪些路由規(guī)則適用于該路由
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
利用Node.js和MySQL實現創(chuàng)建API服務器
這篇文章主要為大家詳細介紹了如何使用Node.js和MySQL創(chuàng)建API服務器的步驟,這也是從前端邁向全棧的一個開始,文中的示例代碼講解詳細,感興趣的小伙伴可以了解下2024-01-01
用純Node.JS彈出Windows系統(tǒng)消息提示框實例(MessageBox)
這篇文章主要介紹了用純Node.JS彈出Windows系統(tǒng)消息提示框實例(MessageBox),非常具有實用價值,需要的朋友可以參考下2017-05-05

