①.安裝node運行環(huán)境
②.使用node.js創(chuàng)建軟件層面上的網(wǎng)站服務(wù)器:要得到請求對象和響應(yīng)對象。
1.1創(chuàng)建web服務(wù)器
// 引用系統(tǒng)模塊
const http = require('http');
// 創(chuàng)建web服務(wù)器
const app = http.createServer();
// 當客戶端發(fā)送請求的時候
app.on('request',(req,res) =>{? ? ? ? ? ? ? ? ? ? ? ?// request 事件名稱 ?req是?request?的簡寫
? ? ? // 響應(yīng)
res.end('<h1>hi,user</h1>');? ? ? ? ? ? ? ? ? ? ? ? //res代表響應(yīng)對象
});
// 監(jiān)聽3000端口
app.listen(3000);
console.log('服務(wù)器已啟動,監(jiān)聽3000端口碉克,請訪問localhost:3000');
ps:node.js基于事件驅(qū)動的語言咱揍。(當什么時候钥勋,做什么事)惭适。
添加請求語法:on('事件處理名稱','事件處理函數(shù)')康栈;
當有請求來時递递,使用end()方法做出響應(yīng):end('響應(yīng)內(nèi)容')喷橙;
監(jiān)聽端口語法:listen(端口號)? ? ? ? ? ?// node開發(fā)習慣使用3000
驗證代碼:
新建文件夾server,其下新建文件app.js
const http = require('http');
const app = http.createServer();? ? ? ? ? // 網(wǎng)站服務(wù)器對象接收到app
app.on('request',(req,res) =>{? ? ? ? ? ? ? // 客戶端有請求來時
res.end('<h2>hi,user</h2>');? ? ? ? ? ? ? // 只要有請求登舞,就返回 hi,user? ? ??
});
app.listen(3000);? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?// 監(jiān)聽端口贰逾,向外界提供服務(wù)
console.log('服務(wù)器已啟動,監(jiān)聽3000端口菠秒,請訪問localhost:3000');?
命令行工具:PS C:\Node\server> node app.js? ? (使用nodemon app.js疙剑,好處只要修改了文件,命令行工具就會重新幫我們執(zhí)行)
輸出:網(wǎng)站服務(wù)器啟動成功
瀏覽器中訪問網(wǎng)站:localhost:3000
輸出:<h2>hi,user</h2>