1)初步介紹
模塊的介紹
- express 主要模塊
- body-parser 處理json,raw,url編碼的數(shù)據(jù)
- cookie-parser cookie的使用模塊
- multer 處理enctype="multipart/form-data"的表單數(shù)據(jù) 言外之意處理有上傳功能的表單
2)初步應(yīng)用
var express = require('express');
var app = express();
//分配路由
app.get('/',function(req,res){
res.writeHead(200,{'Content-Type':'text/plain'});
res.write('Hello Express');
res.end()
})
app.get('/list',function(req,res){
res.writeHead(200,{'Content-Type':'text/html;charset=utf8'});
res.write('這是列表頁');
res.end()
})
//監(jiān)聽端口
app.listen(5000,function(){
console.log('應(yīng)用成功!');
})
分別訪問localhsot:5000和localhsot:5000/list
3)渲染本地html網(wǎng)頁發(fā)布上web服務(wù)器上
先在本地創(chuàng)建index.html網(wǎng)頁其中先不需要外鏈資源文件例如link
var express= require('express'),fs = require('fs');
var app = express();
app.get('/',function(req,res){
fs.readFile(path,function(err,chunk){
if(err){
console.log('請求出錯)
}else{
res.writeHead(200,{'Content-Type':'text/html;charset=utf8'});
res.write(chunk.toString()) //=>Buffer對象轉(zhuǎn)換
res.end();
}
})
})
app.listen(5000,function(){
console.log('應(yīng)用成功!');
})
直接訪問localhost:5000即可訪問到寫的index.html網(wǎng)頁
4)解決上面的外鏈資源文件 static
app.use(express.static(path)) 注意此處有坑?。?!
var express= require('express');
var app = express();
app.use(express.static('img')) //設(shè)置靜態(tài)資源文件
app.get('/',function(req,res){
res.writeHead(200,{'Content-Type':'text/html;charset=utf8'});
res.write('金泰資源文件') //=>Buffer對象轉(zhuǎn)換
res.end();
})
app.listen(5000,function(){
console.log('應(yīng)用成功!');
})
訪問localhost:5000/logo.jpg可以正常訪問到圖片
而當(dāng)我們使用剛剛的use里面的路徑localhost:5000/img/logo.jpg就找不到該文件!
知道這個之后 在index.html里面鏈接的時候就可以注意點(diǎn)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="css/index.css">
<style>
div{
background: blue;
width: 400px;
height: 500px;
margin:100px auto 0;
}
</style>
</head>
<body>
<div id="box">
你好啊
</div>
<img src="runoob-logo.png" alt=""> <!-注意這里的img地址-->
</body>
</html>
image.png
創(chuàng)建server.js
/*express 設(shè)置靜態(tài)文件的請求!??!例如網(wǎng)站的css文件啊 一些img文件夾下的圖片啊*/
var express = require('express'),fs = require('fs');
var app = express();
app.use(express.static('./css')); //此時設(shè)置的靜態(tài)資源路徑是css
app.get('/',function (req,res) {
fs.readFile('./index.html',function (err,chunk) {
if(err){
res.writeHead(404,{'Content-Type':'text/html;charset=utf8'});
res.write('404頁面找不到了!')
res.end();
}else{
res.writeHead(200,{'Content-Type':'text/html;charset=utf8'});
res.write(chunk.toString())
res.end()
}
})
})
app.listen(5000,function () {
console.log('express設(shè)置靜態(tài)文件資源')
})