一:http模塊
http模塊是node的常用模塊,可以用瀏覽器訪問寫的代碼
1.引進http模塊(核心模塊不需要安裝)
let http = require("http")
2.創(chuàng)建服務器(參數接受函數)
let server = http.createServer((req, res)=>{
// 返回結果(狀態(tài)碼,返回類型, 返回的編碼)
res.writeHead(200,{"Content-type": "text/html"; charset=UTF-8})
// 瀏覽器內容
res.write("111")
res.write("<h1>哈哈哈哈哈</h1>")
res.end("hello")
})
3.監(jiān)聽(知道訪問,參數端口號,地址locallhost)
server.listen(80, "127.0.0.1")
二:路由
1.node只能通過控制url來控制跳轉,在服務器端先配置好路由
2.配置路由
引入讀寫操作文件
let fs = require(fs)
let server = http.createServer((req, res)=>{
if (req.url==='/test1.html') { // 瀏覽器地址欄的路由url
console.log(111)
// 讀入文件
fs.readFile("./test1.html", (err, data)=>{
if (!err){
console.log(data.toString)
res.writeHead(200,{"Content-type": "text/html"; charset=UTF-8})
res.end(data)
}
})
} else if (req.url==='/test2.html') {
console.log(222)
// 讀入文件
fs.readFile("./test2.html", (err, data)=>{
if (!err){
console.log(data.toString)
res.writeHead(200,{"Content-type": "text/html"; charset=UTF-8})
res.end(data)
}
})
} else if (req.url==='/') {
}else {
// 返回結果(狀態(tài)碼,返回類型, 返回的編碼)
res.writeHead(404,{"Content-type": "text/html"; charset=UTF-8})
// 瀏覽器內容
res.end("訪問頁面不存在")
}
})
3.node中加載其他類型資源
---除了html和js文件除外的類型文件的訪問
比如css文件,img圖片, 音頻等,要用fs讀到服務中如下
let server = http.createServer((req, res)=>{
if (req.url==='/test1.html') { // 瀏覽器地址欄的路由url, 路由1
console.log(111)
// 讀入文件
fs.readFile("./test1.html", (err, data)=>{
if (!err){
console.log(data.toString)
res.writeHead(200,{"Content-type": "text/html"; charset=UTF-8})
res.end(data)
}
})
} else if (req.url==='/test2.html') { // 瀏覽器地址欄的路由url, 路由2
console.log(222)
// 讀入文件
fs.readFile("./test2.html", (err, data)=>{
if (!err){
console.log(data.toString)
res.writeHead(200,{"Content-type": "text/html"; charset=UTF-8})
res.end(data)
}
})
} else if (req.url==='/css/index/.css') { // css
// 讀css文件
fs.readFile("./css/index/.css", (err, data)=>{
if (!err){
console.log(data.toString)
res.writeHead(200,{"Content-type": "text/css"}) // text/css
res.end(data)
}
})
}else if (req.url==='/img/lixiaoyu.png') { // 圖片
// 讀圖片文件
fs.readFile("./img/lixiaoyu.png", (err, data)=>{
if (!err){
console.log(data.toString)
res.writeHead(200,{"Content-type": "image/jpg"}) // image/jpg
res.end(data)
}
})
} else {
// 返回結果(狀態(tài)碼,返回類型, 返回的編碼)
res.writeHead(404,{"Content-type": "text/html"; charset=UTF-8})
// 瀏覽器內容
res.end("訪問頁面不存在")
}
})
小節(jié)圖如下:
image