在node中http是什么有什么作用
http這個模塊的職責就是幫你創建撰寫服務器
執行流程
1. 加載http模塊
const http = require('http')
2. 使用http.createServer方法創建一個web服務器 回傳一個server實體
const server = http.createServer()
3.提供對資料的服務
發請求
接受請求
處理請求
回傳(發送回應)
注冊request請求事件,當客戶端請求過來就會自動觸發request請求事件然后就會執行第二個引數執行回呼函式
server.on('request',function(){
console.log('收到客戶端的請求了')
})
4.系結埠號,啟動服務器
server.listen(3000,()=> {
console.log("服務器啟動成功了,可以通過http://127.0.0.1:3000/來訪問了")
})
5. node app.js啟動成功
打開瀏覽器復制粘貼http://127.0.0.1:3000/就會發現瀏覽器一直在轉圈(此時已經與瀏覽器建立了鏈接),同時終端回傳收到客戶端的請求了,關閉終端ctrl+c則會終止瀏覽器服務((瀏覽器就不轉圈了,終止連接了))
搭建一個基本的web服務器請求
代碼如下:
const http = require('http')
const server = http.createServer()
// request請求事件處理函式需要接收倆個引數
// request請求物件
// 請求物件可以獲取客戶端的一些請求資訊,例如請求路徑
// response回應物件
// 回應物件可以用來給客戶端發送回應訊息
server.on('request',function(request,response){
console.log('收到客戶端的請求了','請求路徑是:'+request.url)
// response物件有一個方法,write可以用來給客戶端發送回應資料
// write可以使用多次,但是最后一次一定要用end來結束回應,否則客戶端會一直等待
response.write("hello ")
response.write("nodejs")
response.end()
//告訴客戶端我的話說完了你可以給用戶看了
//由于現在我們的服務器能力很弱,無論是什么請求都只能回應hello nodejs
// 怎么做到請求不同的路徑回應不同的結果
})
server.listen(3000,()=> {
console.log("服務器啟動成功了,可以通過http://127.0.0.1:3000/")
})
接下來就是撰寫一個基本的介面資料用來請求
判斷在不同的頁面顯示不同的資料
首頁資料

a頁面資料
…與首頁不同的資料
const http = require("http")
const server = http.createServer()
server.on('request',function(req,res){
res.writeHead(200,{'Content-Type':'text/plain;charset=utf-8'})
console.log("收到請求了,請求路徑是:"+req.url)
// res.write("heel")
// res.write("world")
// res.end()
// 上面的方式比較麻煩
//可以使用end的時候發送回應
// 根據不同的請求路徑發送不同的請求結果
//1. 獲取請求的路徑
// req.url獲取到的是埠號之后的路徑
// 也就是說所有的url都是以/開頭的
//2. 判斷路徑處理回應
const url = req.url
if(url=="/"){
const project = [
{
name:"蘋果",
price:"18",
},
{
name:"香蕉",
price:"28",
},
{
name:"西瓜",
price:"20",
},
{
name:"xxx",
price:"100",
},
{
name:"aaa",
price:"100",
}
]
// 回應資料只能是二進制資料或者是字串
// 回應資料如果是以下的則不行:數字物件陣列布林值
res.end(JSON.stringify(project))
}else if(url=='/a'){
const a = [
{
name:"蘋果",
price:"aa",
},
{
name:"香蕉",
price:"ww",
},
{
name:"西瓜",
price:"vv",
},
{
name:"wjcx",
price:"bb",
},
{
name:"wdwa",
price:"ww",
}
]
res.end(JSON.stringify(a))
}
})
server.listen(3000,function(){
console.log("服務器啟動成功,可以訪問啦!http://127.0.0.1:3000/")
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/299695.html
標籤:其他
