node筆記 --祈粼
流程
1. 引入模塊 通過(guò)變量來(lái)接收
2. 通過(guò)http.createServer創(chuàng)建服務(wù),注意后面跟上一個(gè)匿名函數(shù)
req: request 請(qǐng)求
res: response 響應(yīng)
3. 通過(guò)server.listen監(jiān)聽了端口號(hào)和訪問地址
4. 通過(guò)res.writeHead 設(shè)置網(wǎng)頁(yè)狀態(tài)碼和文檔內(nèi)容類型
5. 通過(guò)res.end 返回結(jié)果
*/
// 啟動(dòng)文件: node xxx.js
var http = require('http') // 變量http得到被引入模塊'http'所有的接口
// 創(chuàng)建服務(wù)器,當(dāng)有請(qǐng)求過(guò)來(lái)的時(shí)候處理
var server = http.createServer(function (req, res) {
/*
設(shè)置響應(yīng)http頭部信息
第一個(gè)參數(shù): 傳入網(wǎng)頁(yè)狀態(tài)碼, 200表示請(qǐng)求正常
第二個(gè)參數(shù): 設(shè)置文檔內(nèi)容類型: text/html 表示html類型, charset = UTF-8 表示文檔編碼類型
小知識(shí): 國(guó)內(nèi)編碼: GBK
*/
res.writeHead(200, { "Content-type": "text/html;charset=UTF-8" })
console.log('服務(wù)器接收到了請(qǐng)求,地址為:' + req.url) // 會(huì)走2次
// 讀取文件和css
fs.readFile('./resource/yuan.html', (err, data) => {
res.writeHead(200, { 'Content-type': 'text/html;charset=UTF-8' })
res.end(data)
})
fs.readFile('./resource/css/yuan.css', (err, data) => {
res.writeHead(200, { 'Content-type': 'text/css' })
res.end(data)
})
/*
注意點(diǎn)
1. Node沒有web容器概念
不管localhost:3000/后面加什么都不會(huì)報(bào)錯(cuò) 也不會(huì)有任何區(qū)別 訪問的都是同一個(gè)頁(yè)面
*/
res.end('hello world!')
// 如果沒有end會(huì)存在'掛起'狀態(tài),瀏覽器tab選項(xiàng)上有個(gè)圈圈在轉(zhuǎn)動(dòng)
})
server.listen(3000, '127.0.0.1')
/*
服務(wù)器默認(rèn)端口號(hào):80端口
Tomcat默認(rèn)端口:8080
*/