首先聲明一個(gè)變量http將nodejs的http模塊通過(guò)require方法引入并賦值給http變量。
var http=require('http');
下面調(diào)用nodejs里面的createServer方法創(chuàng)建web server圣拄。我們需要向這個(gè)方法里面?zhèn)鬟fhttp消息包竹,通過(guò)一個(gè)函數(shù)的方式來(lái)傳遞。這是nodejs文檔中說(shuō)明的方法恢暖。然后讓計(jì)算機(jī)在8000端口監(jiān)聽(tīng)這個(gè)web server。
http.createServer(function(request,response){}).listen(8000);
response.writeHead(200,{'Content-Type':'text/plain'});
response.end('Hello World\n');
}).listen(8000);```
在函數(shù)當(dāng)中,通過(guò)response.writeHead傳遞HTTP信息的頭部信息(這部分需要了解http協(xié)議)
response.end()用來(lái)最后打印出字符叉谜。
最后的```console.log('Server running at http://127.0.0.1:8000/');```用來(lái)在命令提示符狀態(tài)下提示web server已經(jīng)開(kāi)啟。
![Http](http://upload-images.jianshu.io/upload_images/677473-b2392b6472733e79.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![執(zhí)行](http://upload-images.jianshu.io/upload_images/677473-21243e45a0625563.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![服務(wù)器響應(yīng)成功](http://upload-images.jianshu.io/upload_images/677473-c7f143214857a3fe.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)