http请求 url 竖线_http.createServer创建http服务
生活随笔
收集整理的這篇文章主要介紹了
http请求 url 竖线_http.createServer创建http服务
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
語法:
http.createServer([options][, requestListener])第二個(gè)參數(shù)requestListener,是一個(gè)自動(dòng)添加到'request'事件的方法。返回一個(gè)新的 http.Server實(shí)例。
之前代碼是使用==server.on('request',callback)==來監(jiān)聽請(qǐng)求事件,由于http.createServer第二個(gè)參數(shù)也是個(gè)request監(jiān)聽請(qǐng)求事件。所以可以直接把request的請(qǐng)求事件的監(jiān)聽函數(shù)callback傳遞給==http.createServer的第二個(gè)參數(shù)==即可。
代碼如下:
```javascript// 1. 加載http模塊var http = require('http');//2,3步驟寫在一起,可直接把request請(qǐng)求事件的回調(diào)函數(shù)直接定義在createServer函數(shù)中var server = http.createServer(function(req,res){ console.log('有人請(qǐng)求了'); res.end('hello world');})// 4. 啟動(dòng)http服務(wù),開始監(jiān)聽3000端口server.listen(3000, function () { console.log('服務(wù)已經(jīng)啟動(dòng),請(qǐng)?jiān)L問:http://localhost:3000');});```創(chuàng)建http服務(wù)實(shí)現(xiàn)不同請(qǐng)求,響應(yīng)不同內(nèi)容
需求說明
不同的url響應(yīng)不同的內(nèi)容:
請(qǐng)求 / 或 /index,輸出index內(nèi)容
請(qǐng)求 /login,輸出login內(nèi)容
請(qǐng)求 /register,輸出register內(nèi)容
參考代碼
// 1.引入http服務(wù)模塊var http = require('http');// 2.創(chuàng)建服務(wù),設(shè)置監(jiān)聽request事件的回調(diào)函數(shù)var server = http.createServer(function(req, res) { req.url = req.url.toLowerCase(); //把url轉(zhuǎn)為小寫,在賦值給req.url屬性 ? ?if (req.url == '/' || req.url == '/index') { ? res.end('index'); ? }else if(req.url == '/login' ){ ? res.end('login'); ? }else if(req.url == '/register' ){ ? res.end('register'); ? }else{ ? res.end('404 Not Found'); ? }});// 3.啟動(dòng)http服務(wù),監(jiān)聽3000端口server.listen(3000, function() { ? ?console.log('請(qǐng)?jiān)L問http://localhost:3000');});啟動(dòng)服務(wù),輸入http://localhost:3000/login 會(huì)響應(yīng)login內(nèi)容。
總結(jié)
以上是生活随笔為你收集整理的http请求 url 竖线_http.createServer创建http服务的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 广播 消息 没有服务器,服务器节点消息广
- 下一篇: java多个类调用_JAVA问题总结之1