燁竹
簡介
express 是基于node.js web 應用程式的一種開發(fā)框架征堪,可以快速搭建一個功能完整的網站
express.js 是建構在Node.js 中介軟體模組的只洒,我們叫它connect厕鹃,它的運作就是在處理HTTP請求的函數(shù)奸攻;每處理完一個中介軟體函式斤儿,會再傳給下一個中間軟體的函式筛圆。(更多細節(jié)請看:https://goo.gl/ryvrte)
npm uninstall 模塊
刪除本地模塊時你應該思考的問題:是否將在package.json上的相應依賴信息也消除决摧?
npm uninstall 模塊:刪除模塊政基,但不刪除模塊留在package.json中的對應信息
npm uninstall 模塊 --save 刪除模塊思杯,同時刪除模塊留在package.json中dependencies下的對應信息
npm uninstall 模塊 --save-dev 刪除模塊胜蛉,同時刪除模塊留在package.json中devDependencies下的對應信息
安裝express
如果,你要globally 安裝,直接在command prompt 輸入
npm install -g express
Node.js 應用程式初始化誊册,自動加入package.json
在command prompt领突,首先,我們建立一個資料夾:
mkdir myapp
進入該資料夾:
cd myapp
輸入指令:
npm init
根據步驟解虱,輸入與這個應用程式的相關資料攘须,它會以詢答的方式讓你寫入一些資訊,幫你建好一個package.json殴泰,myapp這就是你的一個node.js應用程式
自動生成package文件
安裝express套件
npm install express --save
安裝成功
web application
1于宙、Web Server
var express = require('express');
var app = express();
// define routes here..
var server = app.listen(5050, function () {
console.log('Node server is running..');
});
執(zhí)行結果
2、設定路由
用app.get(), app.post(), app.put(), app.delete() 定義了HTTP的GET, POST, PUT, DELETE 的路由請求
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send("<html><body><h1>hello world</h1></body></html>");
});
app.post('/submit-data', function (req, res) {
res.send('POST Request');
});
app.put('/update-data', function (req, res) {
res.send('PUT Request');
});
app.delete('/delete-data', function (req, res) {
res.send('DELETE Request');
});
var server = app.listen(5000, function () {
console.log('Node server is running..');
});
3悍汛、處理post請求
新建index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="/submit-student-data" method="post">
First Name: <input name="firstName" type="text" />
Last Name: <input name="lastName" type="text" />
<input type="submit" />
</form>
</body>
添加body-parser模塊(是用來解析JSON, buffer,字串,及HTTP Post請求提交的url編碼資料)
npm install body-parser -save
安裝成功如下圖:
添加postapp.js
var express = require('express');
var app = express();
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', function (req, res) {
res.sendFile(__dirname+'/index.html'); //回應靜態(tài)文件
});
app.post('/submit-student-data', function (req, res) {
var name = req.body.firstName + ' ' + req.body.lastName;
res.send(name + ' Submitted Successfully!');
});
var server = app.listen(5000, function () {
console.log('Node server is running..');
});
4捞魁、使用靜態(tài)文件app.use()
var express = require('express');
var app = express();
//setting middleware
app.use(express.static(__dirname + '/public')); //Serves resources from public folder
var server = app.listen(5050);
在myapp下新增一個public資料夾,里面存放一些靜態(tài)文件
設立多個靜態(tài)服務
var express = require('express');
var app = express();
app.use(express.static('public'));
//Serves all the request which includes /images in the url from Images folder
app.use('/images', express.static(__dirname + '/Images'));
var server = app.listen(5050);
app.use()第一個參數(shù),images其實就像我們之前講過的路由名稱离咐,
而實體位置是在__dirname /Images
在myapp下新增一個public資料夾谱俭,里面放入style.css;另外再新增一個Images的資料夾宵蛀,里面放入圖片a001.jpg
在http server提供靜態(tài)服務—使用node-static
node-static module是http提供靜態(tài)文件服務的模組昆著。
安裝
npm install -g node-static
cd myapp
npm install node-static --save
安裝以后,我們可以使用node-static 模組了;
var http = require('http');
var nStatic = require('node-static');
var fileServer = new nStatic.Server('./public');
http.createServer(function (req, res) {
fileServer.serve(req, res);
}).listen(5050);
數(shù)據庫交互
Node.js支援多種不同種類的資料庫主要介紹ms-sql和Mongodb
ms-sql
1术陶、安裝msql-driver
npm install mssql -g
cd myapp
npm install mssql --save
查看package.json是否安裝成功凑懂;
2、建立資料庫及資料表
在MS-SQL Server Management (MSSM) 梧宫,新增一個叫做SchoolDB的資料庫接谨,并且新增一個學生資料庫叫做Student。如圖:
添加數(shù)據:
3塘匣、連接資料庫并且回應資料在網頁上
var express=require('express');
var app=express();
app.get('/',function(req,res){
var sql=require('mssql');
//config for your database
var config={
user:'sa',
password:'justlookvvj',
server:'localhost\\SQLEXPRESS', //這邊要注意一下!!
database:'SchoolDB'
};
//connect to your database
sql.connect(config,function (err) {
if(err) console.log(err);
//create Request object
var request=new sql.Request();
request.query('select * from Student',function(err,recordset){
if(err) console.log(err);
//send records as a response
res.send(recordset);
});
});
});
var server=app.listen(5050,function(){
console.log('Server is running!');
});
這個例子我們載入了mssql module脓豪,并且呼叫connect()
方法,透過參數(shù)config
物件忌卤,去連線我們SchoolDB資料庫扫夜。成功連線后,我們用sql.request
物件埠巨,去執(zhí)行"資料表查詢"历谍,并且把資料取出來
MongoDB
MongoDB安裝和操作見:http://www.reibang.com/p/affa876ba35f
安裝Mongo DB driver
npm install mongodb -g
cd myapp
npm install mongodb --save
新增數(shù)據
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
var url = 'mongodb://tester:password@localhost:27017/lxkdb';
// Use connect method to connect to the server
MongoClient.connect(url,{ useNewUrlParser: true }, function(err, db) {
assert.equal(null, err);
var dbo=db.db('lxkdb');
dbo.collection('student',function(err,collection){
collection.insertOne({ id:1, firstName:'Steve', lastName:'Jobs' });
collection.insertOne({ id:2, firstName:'Bill', lastName:'Gates' });
collection.insertOne({ id:3, firstName:'James', lastName:'Bond' });
collection.countDocuments(function(err,count){
if(err) throw err;
console.log('Total Rows:'+count);
});
});
db.close();
});
結果如圖:
修改數(shù)據
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
var url = 'mongodb://tester:password@localhost:27017/lxkdb';
// Use connect method to connect to the server
MongoClient.connect(url,{ useNewUrlParser: true }, function(err, db) {
assert.equal(null, err);
var dbo=db.db('lxkdb');
dbo.collection('student',function(err,collection){
//collection.update
//第一個參數(shù)是要更新的條件,第二個參數(shù)$set:更新的欄位及內容.
//第三個參數(shù)writeConcern辣垒,第四個參數(shù)執(zhí)行update後的callback函式
collection.update({id:2},{ $set: { firstName:'James', lastName:'Gosling'} },
{w:1}, function(err, result){
if(err) throw err;
console.log('Document Updated Successfully');
});
});
db.close();
});
{w:1}的理解:http://aaron-joe-william.iteye.com
結果如圖:
刪除數(shù)據:
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
var url = 'mongodb://tester:password@localhost:27017/lxkdb';
// Use connect method to connect to the server
MongoClient.connect(url,{ useNewUrlParser: true }, function(err, db) {
assert.equal(null, err);
var dbo=db.db('lxkdb');
dbo.collection('student',function(err,collection){
//collection.update
//第一個參數(shù)是要更新的條件望侈,第二個參數(shù)$set:更新的欄位及內容.
//第三個參數(shù)writeConcern,第四個參數(shù)執(zhí)行update後的callback函式
collection.remove({id:2},{w:1},function(err,result){
if(err) throw err;
console.log('Document Removed Successfully!');
});
});
db.close();
});
結果如圖:
查詢數(shù)據
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
var url = 'mongodb://tester:password@localhost:27017/lxkdb';
// Use connect method to connect to the server
MongoClient.connect(url,{ useNewUrlParser: true }, function(err, db) {
assert.equal(null, err);
var dbo=db.db('lxkdb');
dbo.collection('student',function(err,collection){
collection.find({firstName:"James"}).toArray(function(err,items){
if(err) throw err;
console.log(items);
console.log("We found "+items.length+" results!");
});
});
db.close();
});
結果如圖:
!!重要!!
關于更多Collection的操作勋桶,可以參考:Collection Methods脱衙,特別在使用查詢find侥猬,有不同于以往SQL的使用語法
Pug 模板引擎
相關工具:pug轉html ---------html轉pug
模版引擎是幫助我們以最小的code去新增一個Html Template
它可以在客戶端注入一些資料(像是JSON/XML) , Html Template,透過Template Engine產生最后的HTML呈現(xiàn)至瀏覽器
安裝pug樣版
//cd到myapp中
npm install pug --save
//檢查package.json
添加Myviews文件夾捐韩,文件夾下添加pug文件
doctype html
html
head
title Jade Page
body
h1 This page is produced by Jade engine
p some paragraph here..
添加js文件
var express = require('express');
var app = express();
//set view engine
app.set("view engine","pug")
//set view directory
app.set("views","MyViews")
app.get('/', function (req, res) {
res.render('sample'); // render 執(zhí)行pug文件
});
var server = app.listen(3000, function () {
console.log('Node server is running..');
});
綜合以上退唠,要注意的是:
1.pug template必須寫在.pug檔案里
2.將副檔名為.pug的檔案,儲存在網站根目錄下面的views荤胁,express 預設從views資料夾取樣版瞧预。
3.如果要自訂樣版存放資料夾,我們在express server必須使用app.set(“veiws","自訂樣版存放資料夾絕對路徑")
不使用express仅政,執(zhí)行樣版編譯
var http = require('http'); // 1 - Import Node.js core module
var jade= require('pug');
var data=jade.renderFile('./MyViews/sample.pug');
var server = http.createServer(function (req, res) { // 2 - creating server
if (req.url == '/') { //check the URL of the current request
// set response header
res.writeHead(200, { 'Content-Type': 'text/html' });
// set response content
res.write(data);
res.end();
}else
res.end('Invalid Request!');
});
server.listen(3000); //3 - listen for any incoming requests
console.log('Node.js web server at port 3000 is running..')
除了漢字出現(xiàn)亂碼沒什么差別垢油,如圖
pug語法參考:https://pugjs.org/api/getting-started.html
pug與mysql交互(哈哈。其實本人對mysql比較有好感)
樣板語法測試:http://naltatis.github.io/jade-syntax-docs/這個網站你肯定會用到的圆丹;
cd myapp
npm install mssql --save
pug
doctype html
html
head
title=title
body
h1 mysql數(shù)據取出
ul
each item in catenameList
li=item.catename
js
var express=require('express');
var app=express();
//set view engine
app.set("view engine","pug")
//set view directory
app.set("views","MyViews")
app.get('/',function(req,res){
var mysql=require('mysql');
//config for your database
var con = mysql.createConnection({
host: "localhost",
user:'root',
password:'root',
database:'blog'
});
//connect to your database
con.connect(function (err) {
if(err) console.log(err);
con.query('select catename from tp_cate',function(err,recordset){
if(err)
console.log(err);
else
res.render('sample',{catenameList:recordset});
});
});
});
var server=app.listen(3000,function(){
console.log('Server is running!');
});
執(zhí)行結果如下:
更多操作:https://www.w3schools.com/nodejs/nodejs_mysql_select.asp
Pug與mongodb交互
連接mongodb滩愁,取得資料
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Use connect method to connect to the server
module.exports.personList=function(callback){
MongoClient.connect('mongodb://tester:password@localhost:27017/lxkdb'url,{ useNewUrlParser: true }, function(err, db) {
assert.equal(null, err);
var dbo=db.db('lxkdb');
dbo.collection('student',function(err,collection){
collection.find({firstName:"James"}).toArray(function(err,items){
if(err) throw err;
db.close();
callback(items);
});
});
});
}
建立模板
doctype html
html
head
title=title
body
h1 mongodb與pug交互
ul
for item in personList
li= item.id + ":"
p=item.firstName +' '+item.lastName
連接MongoDB,在express執(zhí)行樣版編繹辫封,呈現(xiàn)資料
var mongodata=require('./app.js');
var express=require("express");
var app=express();
//set view engine
app.set("view engine","pug")
//set view directory
app.set("views","MyViews")
mongodata.personList(function(recordset){
//console.log(recordset);
app.get('/',function(req,res){
res.render('sample', { personList:recordset });
});
});
var server=app.listen(3000,function(){
console.log('Server is running!');
});
執(zhí)行如圖:
pug引用bootstrap
下面用bootstraps制作頁頭頁腳(layout)
尋找Bootstrap框架
首先硝枉,我們可以進入網站getbootstrap,點取上方連結Getting started倦微,可以找到喜歡的框架版型
進入獲取源碼
將Html轉換成Jade
進入http://html2jade.vida.io/
將轉換好的額pug文件略作修改:放入layout.pug文件
編寫js代碼
//postapp.js
var mongodata=require('./app.js');
var express=require("express");
var app=express();
//set view engine
app.set("view engine","pug")
//set view directory
app.set("views","MyViews")
//樣式引用
app.use(express.static('public'));
mongodata.personList(function(recordset){
//console.log(recordset);
app.get('/',function(req,res){
res.render('sample', { personList:recordset });
});
});
var server=app.listen(3000,function(){
console.log('Server is running!');
});
//app.js
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Use connect method to connect to the server
module.exports.personList=function(callback){
MongoClient.connect('mongodb://tester:password@localhost:27017/lxkdb',{ useNewUrlParser: true }, function(err, db) {
assert.equal(null, err);
var dbo=db.db('lxkdb');
dbo.collection('student',function(err,collection){
collection.find({firstName:"James"}).toArray(function(err,items){
if(err) throw err;
db.close();
callback(items);
});
});
});
}
套用layout的pug
extends ./layout
block page-header
h1 pug與bootstrap-------二哈
block content
ul
for item in personList
li= item.id + ":"
p=item.firstName +' '+item.lastName
執(zhí)行如下: