1.模塊引入
要使用HTTP服務器和客戶端,必須使用
require('http')
引入模塊,就用require
2.啓動服務端
2.1 服務端代碼編碼
服務代碼編寫,文件爲js格式:
const http=require('http');
let server=http.createServer((req, res)=>{
// req爲request,是客戶端發來請求,res是response,是服務端的迴應
// 區分url,直接寫在文件內做測試——實際寫在其他文件內讀取
switch(req.url){
case '/aaa':
res.write('abc');
break;
case '/bbb':
res.write('dddd');
break;
case '/1.html':
res.write('<html><head></head><body>sdfasfasf</body></html>');
break;
}
// 發完消息後要加一句res.end(),客戶端才知道發完了
res.end();
});
server.listen(8080);
2.2 啓動
cmd端,啓動服務
F:\study\node\www\2019-2-22>node server.js
瀏覽器端,根據監聽的端口,輸入不同的路由得到不同的反饋
http://localhost:8080/aaa
如果服務器端沒有數據返回到客戶端,可以用res.end;
如果服務器端有數據返回到客戶端,必須用res.send,不能用 res.end
3.注意事項
3.1 打印url
url會打印出兩條,其中一條是logo的url
const http=require('http');
let server=http.createServer((req, res)=>{
console.log(req.url)
res.end();
});
server.listen(8080);
3.2 返回狀態碼
writeHeader()
write函數直接寫到了body內,想返回狀態碼,應該用writeHeader
const http=require('http');
const fs=require('fs');
let server=http.createServer((req, res)=>{
fs.readFile(`www${req.url}`, (err, data)=>{
if(err){
res.writeHeader(404); //header——狀態碼的
res.write('Not Found'); //body——給人看的
}else{
res.write(data);
}
res.end();
});
});
server.listen(8080);