- 前端項(xiàng)目 都必須依托于服務(wù)器運(yùn)行
- PHP 依托于 阿帕奇服務(wù)器(xampp中)
- node 是 自己創(chuàng)建服務(wù)器
由官方提供 http 模塊
1. 先引入 官方提供的 http 模塊
let http=require('http');
2. 使用 http 模塊中 createServer() 創(chuàng)建服務(wù)器
createServer() 中 參數(shù)是一個(gè) 回調(diào)函數(shù)
這個(gè)回調(diào)函數(shù) 有 兩個(gè)參數(shù)
第一個(gè)參數(shù) req (請(qǐng)求)
第二個(gè)參數(shù) res (回應(yīng))
let server=http.createServer(function(req,res){
// 配置相應(yīng)信息
// 發(fā)送 請(qǐng)求頭
// res對(duì)象中 writeHead()
res.writeHead(200,{"Content-Type":"text/html;charset=utf-8"});
// 發(fā)送響應(yīng)數(shù)據(jù)
res.write("<h1>你好,這是你人生中創(chuàng)建的第一個(gè)服務(wù)器</h1>");
res.write("<h1>node1</h1>");
res.write("<h1>node2</h1>");
res.write("<h1>node3</h1>");
res.end("<h1>響應(yīng)結(jié)束K某ā3约取锉屈!</h1>");// 結(jié)束響應(yīng)
});
3. 設(shè)置端口號(hào)
let num=8888;
// 4. 監(jiān)聽(tīng)瀏覽器地址欄 使用 server.listen();
// 有兩個(gè)參數(shù) 第一個(gè)參數(shù) 監(jiān)聽(tīng)的端口號(hào) 第二個(gè)參數(shù) 回調(diào)函數(shù)
server.listen(num,function(){
console.log(`server is running at http://127.0.0.1:${num}`);
})