安裝cnpm:
npm config set registry https://registry.npm.taobao.org(永久使用)
npm --registry https://registry.npm.taobao.org install express(臨時使用)
1、安裝 Express
cnpm install express --save 安裝Express并將其保存到依賴列表中
body-parser - node.js 中間件,用于處理 JSON, Raw, Text 和 URL 編碼的數(shù)據(jù)。
cookie-parser - 這就是一個解析Cookie的工具。通過req.cookies可以取到傳過來的cookie,并把它們轉(zhuǎn)成對象。
multer - node.js 中間件,用于處理 enctype="multipart/form-data"(設置表單的MIME編碼)的表單數(shù)據(jù)。
cnpm install body-parser --save
cnpm install cookie-parser --save
cnpm install multer --save
cnpm list express 安裝完后,我們可以查看下 express 使用的版本號:
2、簡單使用
//express_demo.js 文件
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World');
})
//var server = app.listen(3456, "127.0.0.1", function () {})指定ip,一般用的是127.0.0.1
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("應用實例,訪問地址為 http://%s:%s", host, port)
})
在瀏覽器中訪問 http://127.0.0.1:8081,會顯示hello world
Request 對象 - request 對象表示 HTTP 請求,包含了請求查詢字符串,參數(shù),內(nèi)容,HTTP 頭部等屬性
.獲取客戶ip地址:request.ip
.獲取上傳的文件:request.files
Response 對象 - response 對象表示 HTTP 響應,即在接收到請求時向客戶端發(fā)送的 HTTP 響應數(shù)據(jù)
重定向redirect
response.redirect("/hello/anime");//重定向到/hello/anime
.發(fā)送文件sendFile
response.sendFile("/path/to/anime.mp4");
.渲染網(wǎng)頁模板render,即把變換的內(nèi)容加載到網(wǎng)頁.
response.render("index", { message: "Hello World" });//將message變量傳入index模板,值為"Hello World"渲染成HTML網(wǎng)頁
2、路由決定了由誰(指定腳本)去響應客戶端請求。
// /del_user 頁面響應
app.get('/del_user', function (req, res) {
console.log("/del_user 響應 DELETE 請求");
res.send('刪除頁面');
})
// 對頁面 abcd, abxcd, ab123cd, 等響應 GET 請求
app.get('/ab*cd', function(req, res) {
console.log("/ab*cd GET 請求");
res.send('正則匹配');
})
3、靜態(tài)文件express.static 中間件來設置靜態(tài)文件路徑。例如,如果你將圖片, CSS, JavaScript 文件放在 public 目錄下,可以這么寫:
app.use('/public', express.static('public'));
4、GET 、post方法:
index.html內(nèi)容
<html>
<body>
<form action="http://127.0.0.1:8081/process_get" method="GET">
First Name: <input type="text" name="first_name"> <br>
Last Name: <input type="text" name="last_name">
<input type="submit" value="Submit">
</form>
</body>
</html>
server.js
ar express = require('express');
var app = express();
app.use('/public', express.static('public'));
app.get('/index.htm', function (req, res) {
res.sendFile( __dirname + "/" + "index.htm" );
})
app.get('/process_get', function (req, res) {
// 輸出 JSON 格式
var response = {
"first_name":req.query.first_name,
"last_name":req.query.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("應用實例,訪問地址為 http://%s:%s", host, port)
})
5、上傳文件
var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser');
var multer = require('multer');
app.use('/public', express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer({ dest: '/tmp/'}).array('image'));
app.get('/index.htm', function (req, res) {
res.sendFile( __dirname + "/" + "index.htm" );
})
app.post('/file_upload', function (req, res) {
console.log(req.files[0]); // 上傳的文件信息
var des_file = __dirname + "/" + req.files[0].originalname;
fs.readFile( req.files[0].path, function (err, data) {
fs.writeFile(des_file, data, function (err) {
if( err ){
console.log( err );
}else{
response = {
message:'File uploaded successfully',
filename:req.files[0].originalname
};
}
console.log( response );
//中文編碼處理
res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});
res.end( JSON.stringify( response ) );
});
});
})
6、Cookie 管理
var cookieParser = require('cookie-parser')
var util = require('util');
var app = express()
app.use(cookieParser())
app.get('/', function(req, res) {
console.log("Cookies: " + util.inspect(req.cookies));
})
7、添加 favicon.ico
在 public/images 添加文件 favicon.ico
打開 myapp 下的 app.js 在其中添加
var favicon = require('serve-favicon');
app.use(favicon(__dirname+'/public/images/favicon.ico'));
然后通過命令行安裝 serve-favicon
重啟應用即可
8、中間件:處理HTTP請求的函數(shù).
參數(shù)為:
.四個的時候---第一個為錯誤處理,第二個為客戶請求request,第三個為服務器響應respond,第四個為next中間件. 如function(error, request, response, next){}
.三個的時候---第一個客戶請求request,第二個為服務器響應respond,第三個為next中間件. 如function(request, response, next){}
.兩個的時候---第一個客戶請求request,第二個為服務器響應respondfunction. 如function(request, response){}
中間件use
app.use(express.bodyParser());//使用body參數(shù)
app.use(express.methodOverride());//使用函數(shù)覆蓋
app.use(app.router);//使用路由
app.use(function(err, req, res, next){
console.error(err.stack);
res.send(500, 'Something broke!');
});//錯誤內(nèi)容顯示
9、動態(tài)網(wǎng)頁模板views
res.render('index',{title:"最近文章"});
npm install -g express-generator
npm update -g express
express APP_NAME //創(chuàng)建項目
express APP_NAME -e //以ejs作為模板引擎創(chuàng)建項目
將ejs文件(EJS 是一套簡單的模板語言,用普通的 JavaScript 代碼生成 HTML 頁面)改為html
var ejs = require('ejs');
app.engine('.html', ejs.__express);
app.set('view engine', 'html'); //app.set('view engine', 'ejs');
npm install;//在項目文件夾
每次修改代碼后,需要手動重啟服務,可以使用nodemon進行自動重啟
npm install -g nodemon
將package.json文件中的代碼修改為:
"start": "nodemon ./bin/www