node項目都必須依托于服務(wù)器運(yùn)行
PHP依托于apche(阿帕奇)服務(wù)器(xampp中)
node是自己創(chuàng)建服務(wù)器
有官方提供http模塊
const{read}=require('fs');
let http = require('http');
- 2.使用http模塊中createServer() 創(chuàng)建服務(wù)
createServer()中參數(shù)是一個回調(diào)函數(shù)
這個回調(diào)函數(shù)有兩個參數(shù)
第一個參數(shù)req(請求)
第二個參數(shù)res(回應(yīng))
let server = http.createServer(function (req, res) {
// 配置響應(yīng)信息
// 發(fā)送請求頭
// res對象中 writeHead
res.writeHead(200, { "Content-Type": "text/html;charset=utf-8" });
// 發(fā)送響應(yīng)數(shù)據(jù)
res.write("<h1>你好再登,這是你人生中創(chuàng)建的第一個服務(wù)器</h1>");
res.write("<h1>node1</h1>");
res.write("<h1>node2</h1>");
res.write("<h1>node3</h1>");
res.end("<h1>響應(yīng)結(jié)束a小>薹弧J侠獭酝静!</h1>");//結(jié)束相應(yīng)
});
let num=8888;
- 4.監(jiān)聽瀏覽器地址欄们颜,使用server.listen();
有兩個參數(shù)猾愿,第一個參數(shù)監(jiān)聽的端口號突琳。
第二個參數(shù)拯啦,回調(diào)函數(shù)
server.listen(num, function () {
console.log(`server is running at http://127.0.0.1:${num}`);
})