node --watch js文件名:自動運行服務器
http模塊
http.createServer()
定義:用于創(chuàng)建node服務器
- 創(chuàng)建服務端和客戶端通信的方式
- res對象:響應對象够滑,設置響應頭
響應頭:用于通知瀏覽器:狀態(tài)碼 數據類型 數據 其他... - req對象:請求對象,解析請求頭
請求頭:包含了請求的具體信息:
請求方法:get post put delete
請求的數據
請求的地址
其他參數....
語法:
http.createServer(http請求,http響應)
http.createServer((req想许,res)=>{
//1.解析請求
//2.處理響應
res.writeHead()//設置響應頭
})
返回值:請求到的數據
實例:
const server = http.createServer((req,res)=>{//createServer 創(chuàng)建服務器
res.writeHead(200,{"Content-Type":"text/plain"})//響應頭
res.end("響應了")//響應結束提示信息
})
res.wireHead()
定義:設置響應頭信息
語法:
res.writeHead(statusCode[, statusMessage][, headers])
參數:
statusCode<number>:接受數字類型的狀態(tài)碼志于。
statusMessage <string>:它接受任何顯示狀態(tài)消息的字符串留瞳。
headers <Object>:它接受任何函數胡陪、數組或字符串。
返回值:<http.ServerResponse>:它返回對 ServerResponse 的引用颤练,以便可以鏈接調用既忆。
實例:
const server = http.createServer((req,res)=>{//createServer 創(chuàng)建服務器
res.writeHead(200,{"Content-Type":"text/plain"})//響應頭
res.end("響應了")//響應結束提示信息
})
res.end()
定義:設置響應結束提示信息
語法:
res.end(響應結束提示信息)
實例:
const server = http.createServer((req,res)=>{//createServer 創(chuàng)建服務器
res.writeHead(200,{"Content-Type":"text/plain"})//響應頭
res.end("響應了")//響應結束提示信息
})
Content-Type
定義:用于指定響應頭的數據類型
語法:
{“Content-Type:屬性值”}
屬性值:
- text/plain:文本/普通文本
- text/html:文本/html文本
- application/json :JSON文本
返回值:返回指定的數據類型
實例:
const server = http.createServer((req,res)=>{//createServer 創(chuàng)建服務器
res.writeHead(200,{"Content-Type":"text/plain"})//響應頭
res.end("響應了")//響應結束提示信息
})
server.listen()
定義:設置服務器監(jiān)聽端口
語法:
const server.listen(options[, callback])
option:根據用戶需要,它可以是端口,主機患雇,路徑跃脊,積壓,獨占苛吱,readAll酪术,writableAll,ipv6Only等翠储。
callback:它是一個可選參數绘雁,它是作為參數傳遞的回調函數。
返回值:此方法只返回回調函數
實例:
//http模塊:構建服務器的模塊
const http = module.require("node:http")//node: 表示它是一個內置的模塊
//http.createServer((請求,響應)=>{})
const server = http.createServer((req,res)=>{//createServer 創(chuàng)建服務器
res.writeHead(200,{"Content-Type":"text/plain"})//響應頭
res.end("響應了")//響應結束提示信息
})
server.listen(3000,()=>{console.log("Server is running on http:http://127.0.0.1:3000");})//listen:設置服務器的監(jiān)聽
node監(jiān)聽
Node監(jiān)聽就是在不重啟服務器的情況下援所,自動刷新頁面
語法
node --watch 文件地址
實例:
node --watch "./app/index.js"