Nodejs Web网站-请求路径分发
注:192.168.43.43 參數(shù)是 本地局域網(wǎng)分配的 ip地址(這個(gè)參數(shù)也可以省略不寫(xiě))
windows 可通過(guò) ipconfig 查看, Linux 可通過(guò) ifconfig查看
如果省略ip,瀏覽器請(qǐng)求 http://localhost/ 即可。
運(yùn)行結(jié)果:
瀏覽器請(qǐng)求 :http://192.168.43.43:3000/index.html
瀏覽器請(qǐng)求 :http://192.168.43.43:3000/vvcat.html
瀏覽器請(qǐng)求 :http://192.168.43.43:3000/json.html
根據(jù) res.end(req.url) 方法,我們可以進(jìn)行請(qǐng)求路徑分發(fā)操作
const http = require('http'); http.createServer((req,res)=>{if(req.url.startsWith('/index')){ // 根據(jù) startsWith方法 來(lái)判斷瀏覽器請(qǐng)求的文件名前綴// write向客戶端響應(yīng)內(nèi)容,可以寫(xiě)多次res.write('Hello!');res.write('Welcome to home page');// end方法用來(lái)完成響應(yīng),只能執(zhí)行一次res.end(); // 請(qǐng)求每一個(gè)頁(yè)面必須有end結(jié)束,不管end中是否有內(nèi)容}else if(req.url.startsWith('/login')){res.end('Welcome to the login page');}else{res.end('There are no other pages!'); } }).listen(3000,'192.168.43.43',()=>{console.log('服務(wù)啟動(dòng)...'); });注:如果請(qǐng)求頁(yè)面 沒(méi)有 res.end();方法結(jié)束,會(huì)一直處于一個(gè)頁(yè)面加載的狀態(tài)。
運(yùn)行結(jié)果:
瀏覽器請(qǐng)求 :http://192.168.43.43:3000/index.html
瀏覽器請(qǐng)求 :http://192.168.43.43:3000/login.html
瀏覽器請(qǐng)求 :http://192.168.43.43:3000/vvcat.html
解決使用中文頁(yè)面亂碼問(wèn)題
const http = require('http'); http.createServer((req,res)=>{if(req.url.startsWith('/index')){res.writeHead(200,{'Content-Type':'text/plain; charset=utf8' // 在瀏覽器中指定 utf8編碼格式});// write向客戶端響應(yīng)內(nèi)容,可以寫(xiě)多次res.write('你好!');res.write('歡迎來(lái)到index頁(yè)面');// end方法用來(lái)完成響應(yīng),只能執(zhí)行一次res.end();}else if(req.url.startsWith('/login')){res.writeHead(200,{'Content-Type':'text/plain; charset=utf8'});res.end('歡迎來(lái)到login頁(yè)面');}else{res.writeHead(200,{'Content-Type':'text/plain; charset=utf8'});res.end('暫無(wú)其它頁(yè)面');} }).listen(3000,'192.168.43.43',()=>{console.log('服務(wù)啟動(dòng)...'); });運(yùn)行結(jié)果:
總結(jié)
以上是生活随笔為你收集整理的Nodejs Web网站-请求路径分发的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Node.js Buffer静态方法
- 下一篇: Node.js 将Json文件数据转为S