Nodejs Web网站-请求路径分发
生活随笔
收集整理的這篇文章主要介紹了
Nodejs Web网站-请求路径分发
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
const http = require('http'); // 加載 http 模塊
// req對象是Class: http.IncomingMessage的實例對象
// res對象是Class: http.ServerResponse的實例對象
http.createServer((req,res)=>{// req.url可以獲取URL中的路徑(端口之后部分)res.end(req.url);
}).listen(3000,'192.168.43.43',()=>{ // 服務器 監(jiān)聽 192.168.43.43 的 3000端口console.log('服務啟動...');
});
注:192.168.43.43 參數(shù)是 本地局域網(wǎng)分配的 ip地址(這個參數(shù)也可以省略不寫)
windows 可通過 ipconfig 查看, Linux 可通過 ifconfig查看
如果省略ip,瀏覽器請求 http://localhost/ 即可。
運行結(jié)果:
瀏覽器請求 :http://192.168.43.43:3000/index.html
瀏覽器請求 :http://192.168.43.43:3000/vvcat.html
瀏覽器請求 :http://192.168.43.43:3000/json.html
根據(jù) res.end(req.url) 方法,我們可以進行請求路徑分發(fā)操作
const http = require('http'); http.createServer((req,res)=>{if(req.url.startsWith('/index')){ // 根據(jù) startsWith方法 來判斷瀏覽器請求的文件名前綴// write向客戶端響應內(nèi)容,可以寫多次res.write('Hello!');res.write('Welcome to home page');// end方法用來完成響應,只能執(zhí)行一次res.end(); // 請求每一個頁面必須有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('服務啟動...'); });注:如果請求頁面 沒有 res.end();方法結(jié)束,會一直處于一個頁面加載的狀態(tài)。
運行結(jié)果:
瀏覽器請求 :http://192.168.43.43:3000/index.html
瀏覽器請求 :http://192.168.43.43:3000/login.html
瀏覽器請求 :http://192.168.43.43:3000/vvcat.html
解決使用中文頁面亂碼問題
const http = require('http'); http.createServer((req,res)=>{if(req.url.startsWith('/index')){res.writeHead(200,{'Content-Type':'text/plain; charset=utf8' // 在瀏覽器中指定 utf8編碼格式});// write向客戶端響應內(nèi)容,可以寫多次res.write('你好!');res.write('歡迎來到index頁面');// end方法用來完成響應,只能執(zhí)行一次res.end();}else if(req.url.startsWith('/login')){res.writeHead(200,{'Content-Type':'text/plain; charset=utf8'});res.end('歡迎來到login頁面');}else{res.writeHead(200,{'Content-Type':'text/plain; charset=utf8'});res.end('暫無其它頁面');} }).listen(3000,'192.168.43.43',()=>{console.log('服務啟動...'); });運行結(jié)果:
總結(jié)
以上是生活随笔為你收集整理的Nodejs Web网站-请求路径分发的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Node.js Buffer静态方法
- 下一篇: Node.js 将Json文件数据转为S